gpt4 book ai didi

ios - 如何以编程方式向 UITextField.leftView 添加约束?

转载 作者:搜寻专家 更新时间:2023-10-31 22:18:17 26 4
gpt4 key购买 nike

我正在创建一个将图像添加到 UITextField 的 leftView 的函数,下面是我尝试过的代码。

func setLeftImageWithColor(image:UIImage, color:UIColor, textField:UITextField) {
let imageView = UIImageView(image: image)
imageView.backgroundColor = color
imageView.contentMode = UIViewContentMode.center
textField.leftView = imageView
textField.leftViewMode = UITextFieldViewMode.always

let leadingConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.leadingMargin, relatedBy: NSLayoutRelation.equal, toItem: txtUsername, attribute: NSLayoutAttribute.leadingMargin, multiplier: 1, constant: 0)
let topConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.topMargin, relatedBy: NSLayoutRelation.equal, toItem: txtUsername, attribute: NSLayoutAttribute.topMargin, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.bottomMargin, relatedBy: NSLayoutRelation.equal, toItem: txtUsername, attribute: NSLayoutAttribute.topMargin, multiplier: 1, constant: 0)
let aspectRatioConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: imageView, attribute: NSLayoutAttribute.width, multiplier: (txtUsername.frame.size.height / txtUsername.frame.size.width), constant: 0)
NSLayoutConstraint.activate([leadingConstraint, topConstraint, bottomConstraint, aspectRatioConstraint])

}

报错

Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with anchors and because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'

如果我不添加任何约束,那么 View 是这样的

enter image description here

这就是我想要实现的形象

enter image description here

最佳答案

尝试直接在包含 textView 的 View 的 layoutSubviews 中设置框架:

override func layoutSubviews() {
super.layoutSubviews()

textField.leftView?.frame = CGRect(x: 0, y: 0, width: textField.bounds.height, height: textField.bounds.height)
}

更新

根据仅使用约束的请求,让我们看一下 leftView 如何与 UITextField 一起工作。

从实验来看,UITextField 似乎仅在需要时才将其 leftView 添加到其 View 层次结构中。所以简单地做:

textField.leftView = imageView

不会使 imageView 成为 View 层次结构的一部分。这就是如果您尝试在执行此操作后立即创建约束会导致崩溃的原因。

有一种方法可以强制将其置于 View 层次结构中,那就是在 textField 上强制自动布局:

// add it as a leftView
textField.leftView = imageView

// force autolayout on textField
self.textField.setNeedsLayout()
self.textField.layoutIfNeeded()

// add constraints now

关于ios - 如何以编程方式向 UITextField.leftView 添加约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48948206/

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