ios - 在 subview 中居中标签

标签 ios swift

这是我使用 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
}
}

设计如下: design view

我正在为此而烦恼。

============================================= =============

更新项目

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()
}
}

enter image description here

最佳答案

您应该通过设置约束来使用自动布局。以 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 中:

  • 选择您的测试标签
  • 删除标签的所有约束:

enter image description here

您的标签看起来不错。 I 是全宽的,因为您将 StackView 对齐设置为 fill:

您可以将其设置为 center,但这也会影响 stackView 中的所有 View 。如果这 Not Acceptable ,请将标签移出堆栈 View 。

此外,您希望使用标签Alignment` 属性将 UILabel 的文本居中:

enter image description here

关于ios - 在 subview 中居中标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40550685/

相关文章:

iphone - iOS 7 上的 UITableView 部分索引间距

ios - 以编程方式自动布局不起作用

swift - 正确取消 View ​​模型中的任务

ios - 如何根据 UITableViewCells 的高度调整 UITableView 的高度?

swift - iOS Swift - 如何使用 CABasicAnimation 和 CATransform3DRotate 以及 "m34"变换来制作 360 度翻转动画?

ios - 使用 Swift 子类化 UINavigationBar

ios - Google AdMob 返回 "Configuration does not have valid Google App ID"

ios - 使用 [self presentModalViewController : animated:] and black screen

iphone - 在 Fox news iPhone 应用程序中自定义 UINavigationBar

ios - 我在 tableview 上显示的代码中的错误在哪里?