【问题标题】:How UILabel height according to text height in Swift programmaticallyUILabel 高度如何以编程方式在 Swift 中根据文本高度
【发布时间】:2017-09-05 18:29:50
【问题描述】:

我尝试了很多解决方案,但没有得到正确的答案。

这是我的代码:

self.AhadeesView = UILabel()
self.AhadeesView.translatesAutoresizingMaskIntoConstraints = false
self.AhadeesView.backgroundColor = UIColor.orange
self.AhadeesView.numberOfLines = 0
self.AhadeesView.text = NSLocalizedString("TitleAhadees", comment: "Title Ahadees of the App")
self.AhadeesView.textAlignment = .center
self.AhadeesView.font = UIFont(name:"Jameel-Noori-Nastaleeq",size:25)
self.AhadeesView.lineBreakMode = NSLineBreakMode.byWordWrapping
//   self.AhadeesView.sizeToFit()

containerView1.addSubview(AhadeesView)

【问题讨论】:

  • 在调用sizeToFit之前需要给标签一个宽度。
  • 如何给宽度??
  • 像任何视图一样设置它的frame
  • 已经尝试了所有这些解决方案的...

标签: ios swift swift3 uilabel swift4


【解决方案1】:

似乎您错过了显示标签的框架。

self.AhadeesView = UILabel(frame: [your frame value])

框架可以由

创建
let frame = CGRect(x: 0, y: 0, width: 320, height: [height_of_String])

[height_of_String] 可以通过下面的扩展来计算

您可以使用以下扩展方法计算字符串的宽度和高度

extension String {
    //To calculate the height u need to pass the width of the label and the required font size.

    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return ceil(boundingBox.height)
    }

    func width(withConstraintedHeight height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return ceil(boundingBox.width)
     }
}

【讨论】:

  • 使用自定义字体自定义字体文字高度长标签不要调整高度...
  • 你可以将字体传递给这个扩展
  • 这是怎么做到的??
  • 标签的框架在哪里?
猜你喜欢
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多