【问题标题】:Cannot change label position in stackview swift无法在stackview swift中更改标签位置
【发布时间】:2019-01-18 01:06:02
【问题描述】:

我想更改stackview 内标签的X 位置,stackview 内也有一个按钮。但是,我无法更改标签的位置,因为一旦我为标签设置了约束,就会跳出错误并希望我删除约束。

【问题讨论】:

  • 无论如何,如果您不显示任何内容,任何人都可以帮助您。从对您的项目一无所知的人的角度阅读您的问题。添加足够的信息,以便解决问题。
  • 给我们您的布局界面的屏幕截图或分享您如何将视图添加到您的堆栈视图中。

标签: swift label stackview


【解决方案1】:

这是一个带有按钮和标签的堆栈视图示例,标签的 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
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-06
    • 2021-02-05
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多