1
 value = UILabel(frame: CGRect(x: 5 ,y: 5, width:Int(self.view.frame.width - 140) ,height: 16 ))
        value.numberOfLines = 0
        value.font = UIFont.systemFont(ofSize: 14.0)
       value.lineBreakMode = .byWordWrapping
        value.text = ((items["comment"] as? String) ?? "")!
        value.setLineHeight(lineHeight: CGFloat(1))
        var lineCount = 0;
        let textSize = CGSize(width: value.frame.size.width, height: CGFloat(Float.infinity));
        let rHeight = lroundf(Float(value.sizeThatFits(textSize).height))
        let charSize = lroundf(Float(value.font.lineHeight));

        lineCount = rHeight/charSize
        print(lineCount)
       }

When Trying to get number of lines in that UILabel. it is always giving me one more that the actual line count..

extension UILabel {
func setLineHeight(lineHeight: CGFloat) {
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 1.0
    paragraphStyle.lineHeightMultiple = lineHeight
    paragraphStyle.alignment = self.textAlignment

    let attrString = NSMutableAttributedString(string: self.text!)
    attrString.addAttribute(NSFontAttributeName, value: self.font, range: NSMakeRange(0, attrString.length))
    attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
    self.attributedText = attrString
}

}

hatim
  • 218
  • 4
  • 16
  • Try using attributed string. http://stackoverflow.com/questions/14409897/how-to-calculate-the-height-of-an-nsattributedstring-with-given-width-in-ios-6 – Aks Oct 19 '16 at 08:56
  • Sorry @Aks i did not get You?.. I saw that link..but i am only interested in line count – hatim Oct 19 '16 at 09:24
  • can you share the code for the setLineHeight method – Naveen Ramanathan Oct 19 '16 at 10:39
  • @NaveenRamanathan yea sure but if i remove that also its not giving me correct answer.. See my Edited Question – hatim Oct 19 '16 at 11:38

2 Answers2

0

Check this code. This calculates the no of lines correctly. I have tested it in XCode 8

value = UILabel(frame: CGRect(x: 50 ,y: 50, width:Int(self.view.frame.width - 140) ,height: 400 ))
value.numberOfLines = 0
value.font = UIFont.systemFont(ofSize: 14.0)
value.lineBreakMode = .byWordWrapping
value.text = ((items["comment"] as? String) ?? "")!
let textSize = CGSize(width: value.frame.size.width, height: CGFloat(Float.infinity));
let rHeight = Float(value.sizeThatFits(textSize).height)
var lineCount:Float = 0;
let charSize = Float(value.font.lineHeight)
lineCount = floor(rHeight / charSize)
print("lineCount \(lineCount)")
Naveen Ramanathan
  • 2,166
  • 1
  • 19
  • 21
0

I know this is probably way too late for your needs, but I think the issue is your lineHeightMultiple.

Eric
  • 5,323
  • 6
  • 30
  • 35