2016-04-15 3 views
3

im пытается вычислить высоту UILabel с атрибутом LineSpacing. Странно то, что вычисленное значение высоты нормального ярлыка .text ниже, чем label.attributedText с его линией. похоже, что я делаю что-то неправильно, но не могу найти что-нибудь, поэтому, пожалуйста, помогите: D.Как рассчитать высоту nsattributed строки с динамическим расстоянием динамически

Предоставленный код специально создан для SO, чтобы сделать его компактным и понятным, он реализован по-разному в моем проекте.

extension NSAttributedString { 
    func heightWithWidth(width: CGFloat) -> CGFloat { 
     let maxSize = CGSize(width: width, height: CGFloat.max) 

     let boundingBox = self.boundingRectWithSize(maxSize, options: [.UsesLineFragmentOrigin, .UsesFontLeading, .UsesDeviceMetrics], context: nil) 

     return boundingBox.height 
    } 
} 

extension UILabel { 

    func getHeightWidthGivenWidthAndLineHeight(lineHeight: CGFloat, labelWidth: CGFloat) -> CGFloat { 
     let text = self.text 
     if let text = text { 
      let attributeString = NSMutableAttributedString(string: text) 
      let style = NSMutableParagraphStyle() 

      style.lineSpacing = lineHeight 
      attributeString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSMakeRange(0, text.characters.count)) 
      let height = attributeString.heightWithWidth(labelWidth) 
      self.attributedText = attributeString 
      return height 
     } 
     return 0 
    } 

Я называю это по

let contentHeight = contentLabel.text! == "" ? 0 : contentLabel.getHeightWidthGivenWidthAndLineHeight(3, labelWidth: labelWidth) 

Работа с нормальными строками (без пробелов), отлично работает, когда я использую attributedstring с LineSpacing, если не удается тэ вычислить правильное значение.

ответ

3

Вы можете использовать только размер шрифта UILabel. Например:

let text = "This is\nSome\nGreat\nText" 

    let contentHeight = contentLabel.text! == "" ? 0 : contentLabel.getHeightWidthGivenWidthAndLineHeight(6, labelWidth: labelWidth) 
    //returns 73.2 

Но только установка

contentLabel.attributedText = contentLabel.attributedString //attributedString is same as getHeightWidthGivenWidthAndLineHeight 

    let size = contentLabel.sizeThatFits(contentLabel.frame.size) 
    //returns (w 49.5,h 99.5) 

Код для attributedString добавлены в расширении, если вам нужно, чтобы увидеть, что:

var attributedString:NSAttributedString?{ 
     if let text = self.text{ 
      let attributeString = NSMutableAttributedString(string: text) 
      let style = NSMutableParagraphStyle() 

      style.lineSpacing = 6 
      attributeString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSMakeRange(0, text.characters.count)) 
      return attributeString 
     } 
     return nil 
    } 
+0

Thanx, не знал, что SizeThatFits() работал таким образом :). Я обновляю расширение, чтобы установить высоту строки и вернуть высоту, необходимую для uilabel, используя SizeThatFits() – MQoder

0

Я обновил свой Extension этот способ установить высоту линии и одновременно вернуть новую высоту этикетки. Thanx to beyowulf

extension UILabel { 

    func setLineHeight(lineHeight: CGFloat, labelWidth: CGFloat) -> CGFloat { 
     let text = self.text 
     if let text = text { 
      let attributeString = NSMutableAttributedString(string: text) 
      let style = NSMutableParagraphStyle() 

      style.lineSpacing = lineHeight 
      attributeString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSMakeRange(0, text.characters.count)) 
      self.attributedText = attributeString 
      return self.sizeThatFits(CGSize(width: labelWidth, height: 20)).height 
     } 
     return 0 
    } 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^