iOS-在UITextField中以编程方式定位UIImageView,并自动布局



我想以编程方式添加一个图像视图(选中标记)作为一个文本字段的子视图。由于我对所有视图都使用自动布局,所以我希望使用约束来定位此子视图。这是代码:

class UIFormTextField: UITextField {
    lazy var checkMarkView = UIImageView(image: UIImage(named: "BarButtonItemCheck"))
    func setCheckMarkView() {
        self.addSubview(checkMarkView)
        self.addConstraints([
            NSLayoutConstraint(item: checkMarkView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: CGFloat(1), constant: CGFloat(0)),
            NSLayoutConstraint(item: checkMarkView, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: CGFloat(1), constant: -UIStyle.Size.standardHorizontalSpacing)
            ])
    }
}

我在viewDidLoad函数中调用了setCheckMarkView,但它不起作用。我收到了一个警告:"可能下面列表中至少有一个约束是你不想要的。"

以下是列表,不过我不明白为什么其他约束会干扰新视图。

"<NSAutoresizingMaskLayoutConstraint:0x15084acf0 h=--& v=--& UIImageView:0x15089f4d0.midX == + 12>",
"<NSAutoresizingMaskLayoutConstraint:0x14f691d70 h=--& v=--& H:[UIImageView:0x15089f4d0(24)]>",
"<NSLayoutConstraint:0x1509c54e0 H:[Bruce.UIFormTextField:0x150895520]-(0)-|   (Names: '|':Bruce.UIForm:0x150998430 )>",
"<NSLayoutConstraint:0x1509a6120 H:|-(0)-[Bruce.UIFormTextField:0x150895520]   (Names: '|':Bruce.UIForm:0x150998430 )>",
"<NSLayoutConstraint:0x14f593e20 H:[Bruce.UIForm:0x150998430]-(0)-|   (Names: '|':UIView:0x1509c92d0 )>",
"<NSLayoutConstraint:0x150950f10 H:|-(0)-[Bruce.UIForm:0x150998430]   (Names: '|':UIView:0x1509c92d0 )>",
"<NSLayoutConstraint:0x14f6143b0 UIView:0x1509c92d0.width == UIView:0x15094e8f0.width>",
"<NSLayoutConstraint:0x150813210 UIImageView:0x15089f4d0.trailing == Bruce.UIFormTextField:0x150895520.trailing - 20>",
"<NSLayoutConstraint:0x150896350 'UIView-Encapsulated-Layout-Width' H:[UIView:0x15094e8f0(320)]>"

感谢您的帮助,

问题是您需要禁用imageView上的translatesAutoresizingMaskIntoConstraints属性。这就是为什么你会看到约束的"NSAutoresizingMaskLayoutConstraint"问题

更新后的代码:

lazy var checkMarkView: UIImageView = {
    let imageView = UIImageView(image: UIImage(named: "BarButtonItemCheck"))
    imageView.translatesAutoresizingMaskIntoConstraints = false
    return imageView
}()

编辑:实际上,您不需要禁用声明checkMarkView的属性。您也可以在您的功能"setCheckMarkView"中进行,即

func setCheckMarkView() {
    checkMarkView.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(checkMarkView)
    self.addConstraints([
        NSLayoutConstraint(item: checkMarkView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: CGFloat(1), constant: CGFloat(0)),
        NSLayoutConstraint(item: checkMarkView, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: CGFloat(1), constant: -UIStyle.Size.standardHorizontalSpacing)
        ])
}

最新更新