gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:36:56 24 4
gpt4 key购买 nike

我正在尝试为我拥有的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com