簡體   English   中英

在子視圖中居中放置標簽

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM