这是我使用 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()
}
}
最佳答案
您应该通过设置约束来使用自动布局。以 Storyboard为例。
删除答案中可见的大部分
testLabel
代码:类 View Controller :UIViewController {
// MARK: Properties @IBOutlet weak var testLabel: UILabel! // MARK: Actions @IBAction func trackButton(_ sender: UIButton) { testLabel.text = Track.createTrack().toText() }
在 Storyboard 中:
- 选择您的
测试标签
- 删除标签的所有约束:
您的标签看起来不错。 I 是全宽的,因为您将 StackView
对齐设置为 fill
:
您可以将其设置为 center
,但这也会影响 stackView
中的所有 View 。如果这 Not Acceptable ,请将标签移出堆栈 View 。
此外,您希望使用标签Alignment` 属性将 UILabel 的文本居中:
关于ios - 在 subview 中居中标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40550685/