[英]centering a label in a subview
這些是我使用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
分配為fill
:
您可以將其設置為center
,但這也會影響stackView
的所有視圖。 如果不可接受,請將標簽移出堆棧視圖。
另外,您還想UILabel, using the labels
Alignment`屬性將UILabel, using the labels
的文本居中:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.