无法更改标签视图在Swift中的位置

时间:2019-01-18 01:06:02

标签: swift label stackview

我想更改标签在stackview内的X位置,stackview内也有一个按钮。但是,当我为标签设置约束后,便无法更改标签的位置,错误跳出并希望我删除约束。有人可以帮我吗?谢谢![在此处输入图片描述] [1]

1 个答案:

答案 0 :(得分:0)

这是一个带有按钮和带有更改标签的x位置的标签的堆栈视图的示例。

import UIKit

class ViewController: UIViewController {

    let stackView = UIStackView()

    override func viewDidLoad() {
        super.viewDidLoad()

        stackView.axis = .vertical
        stackView.distribution = .equalSpacing
        stackView.alignment = .center

        view.addSubview(stackView)
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        stackView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        stackView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true

        let button = UIButton()
        button.setTitle("Button", for: .normal)
        button.setTitleColor(UIColor.black, for: .normal)
        button.backgroundColor = UIColor.lightGray
        stackView.addArrangedSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.leftAnchor.constraint(equalTo: stackView.leftAnchor).isActive = true
        button.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true

        let label = UILabel()
        label.text = "Label"
        label.textColor = UIColor.black
        label.backgroundColor = UIColor.lightGray
        stackView.addArrangedSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        // Modify left/right anchor constraints for label x position
        label.leftAnchor.constraint(equalTo: stackView.leftAnchor, constant: 24).isActive = true
        label.rightAnchor.constraint(equalTo: stackView.rightAnchor).isActive = true
    }

}