自动调整锚点不会将子视图设置为角点

时间:2016-09-30 09:16:31

标签: ios swift

我在swift中使用锚点来调整UIButtonUILabel的大小时出现问题。

我现在的观点:

My view right now

我想要标签和按钮来填充整个视图,并留下一个空的空间(“openspace”)。这是我的代码:

import UIKit

class standardLabel: UIView {

    private var label: UILabel!
    private var button: UIButton!

    let openSpace: CGFloat = 4.0

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)

        label = UILabel()
        button = UIButton()

        label.backgroundColor = cLightBlue
        label.textColor = cWhite
        label.textAlignment = .center
        label.font = fBigFont
        button.backgroundColor = cWhite
        button.setTitleColor(cDarkBlue, for: .normal)
        button.titleLabel?.font = fBigCleanFont

        label.translatesAutoresizingMaskIntoConstraints = false
        button.translatesAutoresizingMaskIntoConstraints = false

        addSubview(label)
        addSubview(button)

        setConstraints()

        //layer.masksToBounds = true
        //layer.cornerRadius = cornerRad
        backgroundColor = UIColor.brown//superview?.backgroundColor
    }

    func setTextLabel(text: String) -> Void {
        label.text = text
    }

    func setTextButton(text: String) -> Void {
        button.setTitle(text, for: .normal)
    }

    private func setConstraints() -> Void {
        let margins = layoutMarginsGuide

        label.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
        label.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
        label.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true
        button.topAnchor.constraint(equalTo: margins.topAnchor).isActive = true
        button.bottomAnchor.constraint(equalTo: margins.bottomAnchor).isActive = true
        button.trailingAnchor.constraint(equalTo: margins.trailingAnchor).isActive = true


        label.trailingAnchor.constraint(equalTo: button.leadingAnchor, constant: openSpace).isActive = true
        label.widthAnchor.constraint(equalTo: button.widthAnchor).isActive = true
    }
}

我是否在设置锚点时出错或是否因为我创建了一个单独的类而产生了问题?

2 个答案:

答案 0 :(得分:0)

我尝试了你的代码,它非常好,我发现两个视图之间有4.0,但由于按钮的颜色是白色,你无法看到标签和按钮之间的间距。

尝试将间距增加到20.0,您就会知道其中的差异。

答案 1 :(得分:0)

将锚点设置为self而不是self.layoutMarginsGuide将解决问题。