缺少约束IOS 11 swift 4

问题描述 投票:1回答:1

我正在尝试在两个控件之间添加约束:TextField和Separator。但我看不到分隔符。这段代码有什么问题?

func setupTextField() {
    textField =  UITextField(frame: CGRect(x: 0, y: 0, width: 97, height: 30))
    textField!.backgroundColor = .clear
    textField!.placeholder = placeHolder

    self.addSubview(textField!)

    //MARK: Constraints

    textField!.translatesAutoresizingMaskIntoConstraints = false;
    textField!.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
    textField!.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
    textField!.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}

func setupSeparator() {
    separator = UIView(frame: CGRect(x: 0, y: 32, width: 97, height: 1))
    separator?.backgroundColor = .lightGray

    self.addSubview(separator!)

    separator!.translatesAutoresizingMaskIntoConstraints = false;
    separator!.topAnchor.constraint(equalTo: textField!.bottomAnchor, constant: 1).isActive = true
    separator!.leftAnchor.constraint(equalTo: textField!.leftAnchor).isActive = true
    separator!.rightAnchor.constraint(equalTo: textField!.rightAnchor).isActive = true
}
ios swift constraints
1个回答
2
投票

您需要为分隔符添加高度约束,否则它将被压缩到零高度,这就是您无法看到它的原因。在setupSeparator方法中添加以下内容:

separator!.heightAnchor.constraint(equalToConstant: 1).isActive = true
© www.soinside.com 2019 - 2024. All rights reserved.