尝试设置UITextfield宽度约束的动画,但无法正常工作

时间:2019-10-11 20:03:46

标签: 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
}()

1 个答案:

答案 0 :(得分:1)

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

var widthCon:NSLayoutConstraint! 

从激活块中获取宽度约束

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)
}