在子视图
中心标签这些都是我与iOS在子视图
class ViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var testLabel: UILabel!
// MARK: Events
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
testLabel.numberOfLines = 0
testLabel.sizeToFit()
testLabel.center.x = testLabel.superview!.center.x
//from here the label is centered
}
// MARK: Actions
@IBAction func trackButton(_ sender: UIButton) {
//first call: the label is aligned on the left
//following calls: the label is centered
testLabel.text = Track.createTrack().toText()
//even the following commented code does not allow the centering
//on the first call
//testLabel.sizeToFit()
//testLabel.center.x = testLabel.superview!.center.x
}
}
我拉我的头发了这一点。
============================================== ==============
更新项目
class ViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var testLabel: UILabel!
// MARK: Events
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
//testLabel.numberOfLines = 0
//testLabel.sizeToFit()
//testLabel.center.x = testLabel.superview!.center.x
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Actions
@IBAction func trackButton(_ sender: UIButton) {
testLabel.text = Track.createTrack().toText()
}
}
你应该通过设置限制使用自动布局。在你的情况在故事板。
-
删除在你的答案最
testLabel
代码可见:类的ViewController:UIViewController的{
// MARK: Properties @IBOutlet weak var testLabel: UILabel! // MARK: Actions @IBAction func trackButton(_ sender: UIButton) { testLabel.text = Track.createTrack().toText() }
}
在故事板:
- 选择
Test Label
- 删除标签的所有约束上:
你的标签看起来正确。我是全宽的,因为你的StackView
allignment设置为fill
:
您可以将其设置为center
,但这会影响stackView
还中的所有意见。如果这不可接受,请将标签移出堆栈视图。
此外,要居中的UILabel, using the labels
Alignment`属性的文字:
它不起作用,但扩大了标签宽度,因此保留文本在左侧。 – tschmit007
你能链接到该项目吗?更新了答案。 – shallowThought
如果标签上的约束扩展为填充宽度,并且仍然看到左对齐的文本,那么您是否检查过“界面”构建器中的中央对齐以将其居中在此中央空间内? – elmarko
您需要设置的限制界面生成器。 – rckoenes