代码之家  ›  专栏  ›  技术社区  ›  stevenpcurtis

如何在Swift中使用多行文字将UILabel居中?

  •  0
  • stevenpcurtis  · 技术社区  · 7 年前

    我想通过编程将一个带有多行文本的标签居中。我已将其添加到以下约束中,但它仅显示在一行上!我怎么能让它显示多行而不超过屏幕的边界?

    let noResults = UILabel()
    
    noResults.text = self.emptyMessage
    noResults.lineBreakMode = .byWordWrapping
    
    noResults.minimumScaleFactor = 0.5
    noResults.textAlignment = .center
    noResults.font = UIFont(name: "Montserrat-Light", size: 20.0)!
    noResults.numberOfLines = 0
    noResults.adjustsFontSizeToFitWidth = true
    
    noResults.sizeToFit()
    
    
    noResults.textColor = UIColor.lightGray
    noResults.translatesAutoresizingMaskIntoConstraints = false
    
    self.view.addSubview(noResults)
    
    let yConstraint = NSLayoutConstraint(item: noResults, attribute: .centerY, relatedBy: .equal, toItem: noResults.superview, attribute: .centerY, multiplier: 1, constant: -(self.navigationController?.navigationBar.frame.height)!)
    let xConstraint = NSLayoutConstraint(item: noResults, attribute: .centerX, relatedBy: .equal, toItem: noResults.superview, attribute: .centerX, multiplier: 1, constant: 0)
    
    
    NSLayoutConstraint.activate([yConstraint, xConstraint])
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   CZ54    7 年前

    只需添加宽度约束。

        2
  •  0
  •   Subrat Padhi    7 年前

    你可以用情节提要轻松完成,只需给 UILabel标签 在属性检查器make中 线 属性设置为零(0)。

    snapShot