Swift 3 以编程方式创建 UILabel 并添加 NSLayoutConstraints

Posted

技术标签:

【中文标题】Swift 3 以编程方式创建 UILabel 并添加 NSLayoutConstraints【英文标题】:Swift 3 Create UILabel programmatically and add NSLayoutConstraints 【发布时间】:2016-10-28 06:21:06 【问题描述】:

您好,我正在尝试以编程方式创建一个标签并添加 NSLayoutConstraints 以便它在超级视图中居中,而不管屏幕大小和方向等。我已经看过但找不到可以遵循的示例。这是我所拥有的:

let codedLabel:UILabel = UILabel()
codedLabel.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
codedLabel.textAlignment = .center
codedLabel.text = alertText
codedLabel.numberOfLines=1
codedLabel.textColor=UIColor.red
codedLabel.font=UIFont.systemFont(ofSize: 22)
codedLabel.backgroundColor=UIColor.lightGray

let heightConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)

let widthConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)

codedLabel.addConstraints([heightConstraint, widthConstraint])

let verticalConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)

let horizontalConstraint:NSLayoutConstraint = NSLayoutConstraint(item: codedLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)

self.contentView.addConstraints([verticalConstraint, horizontalConstraint])

self.contentView.addSubview(codedLabel)

【问题讨论】:

要标签垂直和水平居中吗? 【参考方案1】:

NSLayoutAnchor 是 ios 9 中的新功能,它极大地清理了约束语法。

let codedLabel:UILabel = UILabel()
codedLabel.frame = CGRect(x: 100, y: 100, width: 200, height: 200)
codedLabel.textAlignment = .center
codedLabel.text = alertText
codedLabel.numberOfLines=1
codedLabel.textColor=UIColor.red
codedLabel.font=UIFont.systemFont(ofSize: 22)
codedLabel.backgroundColor=UIColor.lightGray

self.contentView.addSubview(codedLabel)
codedLabel.translatesAutoresizingMaskIntoConstraints = false
codedLabel.heightAnchor.constraint(equalToConstant: 200).isActive = true
codedLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
codedLabel.centerXAnchor.constraint(equalTo: codedLabel.superview!.centerXAnchor).isActive = true
codedLabel.centerYAnchor.constraint(equalTo: codedLabel.superview!.centerYAnchor).isActive = true

【讨论】:

谢谢你 在 iOS 10 和 Xcode 8.2 中完美运行。【参考方案2】:

以下代码为例

let lblNew = UILabel()
lblNew.backgroundColor = UIColor.blue
lblNew.text = "Test"
lblNew.textColor = UIColor.white
lblNew.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(lblNew)

let widthConstraint = NSLayoutConstraint(item: lblNew, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 300)
let heightConstraint = NSLayoutConstraint(item: lblNew, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)
var constraints = NSLayoutConstraint.constraints(
    withVisualFormat: "V:[superview]-(<=1)-[label]",
    options: NSLayoutFormatOptions.alignAllCenterX,
    metrics: nil,
    views: ["superview":view, "label":lblNew])

view.addConstraints(constraints)

// Center vertically
constraints = NSLayoutConstraint.constraints(
    withVisualFormat: "H:[superview]-(<=1)-[label]",
    options: NSLayoutFormatOptions.alignAllCenterY,
    metrics: nil,
    views: ["superview":view, "label":lblNew])

view.addConstraints(constraints)

view.addConstraints([ widthConstraint, heightConstraint])

【讨论】:

起初看起来令人生畏,但一旦有人向您展示如何操作,它就会看似简单 - 谢谢 lblNew.translatesAutoresizingMaskIntoConstraints = false 帮了我大忙。【参考方案3】:
let myLabel: UILabel = 
  let lb = UILabel()
  lb.translatesAutoresizingMaskIntoConstraints = false
  lb.textAlignment = .center
  lb.numberOfLines = 1
  lb.textColor = UIColor.black
  lb.font=UIFont.systemFont(ofSize: 22)
  lb.backgroundColor = UIColor.grey
  return lb
()

super.viewDidLoad() 方法中,您需要在视图中添加标签并 为标签添加约束:

override func viewDidLoad() 
  super.viewDidLoad()
  self.view.addSubView(myLabel)
  setUpMyLabel()


func setUpMyLabel() 
  NSLayoutConstraint.activate([
            myLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            myLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            myLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.7),
            myLabel.heightAnchor.constraint(equalToConstant: 50)])

希望我的代码对你有帮助。

【讨论】:

以上是关于Swift 3 以编程方式创建 UILabel 并添加 NSLayoutConstraints的主要内容,如果未能解决你的问题,请参考以下文章

在 iOS 10 + Swift 3 中以编程方式在我的 WKWebView 上方添加 UILabel

在 Swift 中使用 UISlider 以编程方式更改 UILabel

在 Swift 中以编程方式访问和更新 stackview 中的 label.text 或其他 UILabel 属性

如何在 Swift 中以编程方式将 UILabel 对象居中?

UILabel 高度如何以编程方式在 Swift 中根据文本高度

UILabel swift的圆角