试图为 UITextfield 宽度约束设置动画,但它不起作用
Posted
技术标签:
【中文标题】试图为 UITextfield 宽度约束设置动画,但它不起作用【英文标题】:Trying to animate UITextfield width constraint, but it won't work 【发布时间】:2019-10-11 20:03:46 【问题描述】:我正在尝试为 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
()
【问题讨论】:
激活运行后更改searchBarWidth
不会反映到约束的值
【参考方案1】:
你应该改变约束的常量值,所以创建一个 var
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)
【讨论】:
以上是关于试图为 UITextfield 宽度约束设置动画,但它不起作用的主要内容,如果未能解决你的问题,请参考以下文章