gpt4 book ai didi

swift - 以编程方式向自定义组件添加约束

转载 作者:行者123 更新时间:2023-11-28 08:36:53 25 4
gpt4 key购买 nike

我正在通过继承默认组件在 Swift 中开发自定义组件。下面是我的一段代码:

class DirectionButton: UIButton {
var backgroundImage: UIImageView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
styleComponent()
}

override init(frame: CGRect) {
super.init(frame: frame)
styleComponent()
}

func styleComponent() {
backgroundImage = UIImageView(image: UIImage(named: "seta-proximo"))
backgroundImage.contentMode = .ScaleAspectFit
self.setNeedsLayout()
self.layoutIfNeeded()
self.addSubview(backgroundImage)
let imageConstraints = NSLayoutConstraint(item: self, attribute: .TrailingMargin, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 10)
backgroundImage.addConstraint(imageConstraints)
}
}

backgroundImage 变量需要距按钮右侧 10 点,这就是我需要约束的原因。

运行后我得到了这样的异常: View 层次结构没有为约束准备。

如何正确添加约束?

最佳答案

阅读文档后,我按照@AjayBeniwal 建议的提示使用布局 anchor 。我需要的代码如下(在我将 subview 添加到按钮之后):

backgroundImage.trailingAnchor.constraintEqualToAnchor(self.layoutMarginsGuide.trailingAnchor, constant: -10).active = true
backgroundImage.bottomAnchor.constraintEqualToAnchor(self.layoutMarginsGuide.bottomAnchor).active = true
backgroundImage.centerYAnchor.constraintEqualToAnchor(self.layoutMarginsGuide.centerYAnchor).active = true

这样,图像垂直集中在距右边缘 20 点的按钮上。

关于swift - 以编程方式向自定义组件添加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37484328/

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