【问题标题】:How to add constrains inside custom UIView?如何在自定义 UIView 中添加约束?
【发布时间】:2021-05-16 10:14:04
【问题描述】:

我想给 UILabel 添加约束 我的自定义 UIView 类:

class LabelView: UIView {

    public var label: UILabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame = frame
        prepareUI()
    }  
    func prepareUI() {     
        self.label.text = "SOME TEXT"
        self.label.sizeToFit()
        self.label.adjustsFontSizeToFitWidth = true
        self.label.textAlignment = .center
        self.addSubview(self.label)
        
        self.translatesAutoresizingMaskIntoConstraints = false
        self.label.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
        self.label.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        self.label.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.5).isActive = true
        self.label.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.2).isActive = true
    }
}

运行后出现如下错误,UILabel 位于 UIView 的左上角:

2021-02-13 02:32:26.698694+1000 SwiftHello[96793:1625524] [LayoutConstraints] 无法同时满足约束。 以下列表中的至少一个约束可能是您不想要的。 尝试这个: (1)查看每个约束并尝试找出您不期望的; (2) 找到添加了一个或多个不需要的约束的代码并修复它。 (注意:如果您看到不理解的 NSAutoresizingMaskLayoutConstraints,请参阅 UIView 属性 translatesAutoresizingMaskIntoConstraints 的文档) ( "<0x600000606c10 h="--&" v="--&" uilabel:0x142616930.minx="="><0x600000606c60 h="--&" v="--&" uilabel:0x142616930.width="="><0x6000006061c0 uilabel:0x142616930.centerx="=" swifthello.labelview:0x1426167c0.centerx><0x600000606300 uilabel:0x142616930.width="=">

<0x6000006061c0 uilabel:0x142616930.centerx="=" swifthello.labelview:0x1426167c0.centerx>

<0x600000606cb0 h="--&" v="--&" uilabel:0x142616930.miny="="><0x600000606d00 h="--&" v="--&" uilabel:0x142616930.height="="><0x6000006062b0 uilabel:0x142616930.centery="=" swifthello.labelview:0x1426167c0.centery><0x600000606350 uilabel:0x142616930.height="=">

<0x6000006062b0 uilabel:0x142616930.centery="=" swifthello.labelview:0x1426167c0.centery>

<0x600000606c60 h="--&" v="--&" uilabel:0x142616930.width="="><0x600000606300 uilabel:0x142616930.width="="><0x600000606940 swifthello.labelview:0x1426167c0.width="="><0x600000606da0 uiview:0x14260e930.width="=">

<0x600000606300 uilabel:0x142616930.width="=">

<0x600000606d00 h="--&" v="--&" uilabel:0x142616930.height="="><0x600000606350 uilabel:0x142616930.height="="><0x600000606990 swifthello.labelview:0x1426167c0.height="="><0x600000606d50 uiview:0x14260e930.height="=">

<0x600000606350 uilabel:0x142616930.height="=">

    标签: ios swift uiview nslayoutconstraint


    【解决方案1】:

    你错过了这一行:

    self.label.translatesAutoresizingMaskIntoConstraints = false
    

    您已将其设置在 self 上,但未设置在 label 上。

    【讨论】:

    • 糟糕,该睡觉了。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2015-08-26
    • 2016-03-21
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2022-12-17
    • 2022-01-22
    相关资源
    最近更新 更多