我该如何解决无法呈现和更新自动布局状态的问题?在xcode 10.2.1中将约束添加到自定义控件后

时间:2019-07-11 22:33:42

标签: swift xcode macos-mojave

我具有以下自定义控件:

import UIKit
import os.log

@IBDesignable class LocationControl: UIStackView {
    @IBInspectable var nameSize: CGSize = CGSize(width: 100.0, height: 21.0) {
        didSet {
            setupLabels()
        }
    }

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

    required init(coder: NSCoder) {
        super.init(coder: coder)
        setupLabels()
    }

    private func setupLabels() {
        // Create the labels
        let nameLabel = UILabel()
        nameLabel.text = "Name"
        nameLabel.backgroundColor = UIColor.red

        let textLabel = UILabel()
        textLabel.text = "Text"
        textLabel.backgroundColor = UIColor.green

        // Add constraints
        let margins = self.layoutMarginsGuide

        nameLabel.translatesAutoresizingMaskIntoConstraints = false
        nameLabel.heightAnchor.constraint(equalToConstant: nameSize.height).isActive = true
        nameLabel.widthAnchor.constraint(equalToConstant: nameSize.width).isActive = true
//        nameLabel.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true

        self.addSubview(nameLabel)
        self.addSubview(textLabel)
    }
}

此代码可以正常运行(但不符合要求)。如果我取消注释该行

//        nameLabel.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true

然后在标准编辑器中切换到Main.storyboard,出现以下错误:

file:///Users/tim.daley/AixNPanes/iOS/location/location/Base.lproj/Main.storyboard:错误:IB Designables:无法呈现和更新UIViewController的自动布局状态(29D-8H- aV6):代理抛出异常。

我正在macOS Mojave 10.14.5上运行Xcode版本10.2.1(10E1001)

1 个答案:

答案 0 :(得分:0)

您可能需要在约束之前添加视图

self.addSubview(nameLabel)
self.addSubview(textLabel)

nameLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
   nameLabel.heightAnchor.constraint(equalToConstant: nameSize.height),
   nameLabel.widthAnchor.constraint(equalToConstant: nameSize.width),
   nameLabel.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
])