ios - 尝试为 UITextfield 宽度约束设置动画,但它不起作用

标签 ios swift nslayoutconstraint

我正在尝试为我拥有的 UITextfield 的宽度约束设置动画,我想要实现的是在设置动画时使 UITextfield 从宽度 0 到宽度 X。

这是我目前所拥有的:

let MAX_SEARCH_BAR_WIDHT: CGFloat = 285
var searchBarWidth: CGFloat = 0

private func setupSearchBar()  {
    addSubview(searchBar)
    NSLayoutConstraint.activate([
        searchBar.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 8),
        searchBar.trailingAnchor.constraint(equalTo: searchBtn.leadingAnchor, constant: -8),
        searchBar.heightAnchor.constraint(equalToConstant: 30),
        searchBar.widthAnchor.constraint(equalToConstant: searchBarWidth),
    ])
}

这是我尝试为 UITextfield 设置动画的地方:

func handleSearch() {
    mView.isSearchingAlready = !mView.isSearchingAlready
    UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
        self.mView.searchBarWidth += self.mView.MAX_SEARCH_BAR_WIDHT
        self.mView.layoutIfNeeded()
    }, completion: nil)
}

handleSearch 在我点击搜索按钮时被调用。 单击按钮时,UITextfield 不会显示。 这是 UITextfield:

let searchBar: UITextField = {
   let field = UITextField(frame: CGRect(x: 0, y: 0, width: 1, height: 0))
    field.backgroundColor = .appWhite
    field.tintColor = UIColor.clear
    field.translatesAutoresizingMaskIntoConstraints = false
    field.layer.cornerRadius = 15
    field.isHidden = false

    let padding = UIView(frame: CGRect(x: 0, y: 0, width: 8, height: 1))
    field.leftView = padding
    field.leftViewMode = .always
    field.rightView = padding
    field.rightViewMode = .always

    field.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("searchbar.placeholder", comment: "find"), attributes: [NSAttributedString.Key.foregroundColor: UIColor.init(hexString: "#080708", alpha: 0.5)])

    return field
}()

最佳答案

您应该更改约束的常量值,因此创建一个 var

var widthCon:NSLayoutConstraint! 

从激活 block 中获取宽度约束

widthCon = searchBar.widthAnchor.constraint(equalToConstant: searchBarWidth)
widthCon.isActive = true

然后

func handleSearch() {
    mView.isSearchingAlready = !mView.isSearchingAlready
    self.mView.widthcon.constant = self.mView.MAX_SEARCH_BAR_WIDHT
    UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: { 
        self.view.layoutIfNeeded()
    }, completion: nil)
}

关于ios - 尝试为 UITextfield 宽度约束设置动画,但它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58347801/

相关文章:

ios - 检查当前时间是否在午夜后考虑的时间范围内 - Swift

ios - 如何以编程方式添加具有动态宽度的约束

ios - 如何删除突出显示的 pdf 注释?

ios - 上传 APNS 证书的问题 Firebase

ios - 使用多点连接接收消息时如何发出声音通知?

swift - 如何在 Swift 中存储对整数的引用

swift - 快速换行识别

ios - 从日志输出中识别并修复自动布局问题

ios - 如何删除 View 和更新约束?

ios - UITableView 在 iOS 8 中很好,但在 iOS7 中崩溃了