2016-09-16 84 views
0

我想把這個文本「...閱讀更多」當我的標籤文本超過3行,我想阻止我的文字不會被截斷。在UILabel的特定部分添加文字「...閱讀更多」IOS

我嘗試了一些代碼,但我有不同的iPhone寬度問題,我的代碼適用於iPhone 6s,但不適用於iPhone 4s和iPhone 5s。

這裏是我的代碼:

let originalText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tristique ipsum non pretium mollis. Curabitur tristique asfhaksjf sfjhksafhdaf ahsdifhsadfh asdfhsahfoas sdofhasdhfasdf" 

     label.text = originalText 
     let labelWidth = label.frame.size.width * CGFloat(label.numberOfLines) 

     let str = label.text! as NSString 

     let words = str.componentsSeparatedByString(" ") 
     var newStr = "" as NSString 

     for word in words { 
      let statement = "\(newStr) \(word) ... Read more" as NSString 
      let size = statement.sizeWithAttributes([NSFontAttributeName: label.font]) 
      let readMoreStatement = " ... Read more" as NSString 
      let sizeReadMore = readMoreStatement.sizeWithAttributes([NSFontAttributeName : label.font]) 

      if size.width < labelWidth { 

       newStr = "\(newStr) \(word)" 
       label.text = newStr as String 
      } else { 
       newStr = newStr.stringByAppendingString("... Read More") 
       label.text = newStr as String 
       break 
      } 
     } 

這裏是4S結果:

Here is the result on 4s

這裏是6S結果:

Here is the result on 6s

任何建議我如何解決這個問題他們嗎?

回答

0

您需要首先autoConstrains您的標籤和使用下面的代碼

let originalText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tristique ipsum non pretium mollis. Curabitur tristique asfhaksjf sfjhksafhdaf ahsdifhsadfh asdfhsahfoas sdofhasdhfasdf" 

    label.text = originalText 
    print((label.text?.characters.count)!) 

    if (label.text?.characters.count)! < 100 { 

      label.text = originalText 
      label.center = view.center 
      label.textAlignment = .justified 
      label.adjustsFontSizeToFitWidth = true // If you want a dynamic font size 
      label.sizeToFit() 
      print(label.text!) // If character count less then 100 approximately 3 lines 
     } else { 

      label.text = "...Read more" 
      label.textAlignment = .center 
      print(label.text!) //If character count more then 100 exceeds 3 lines   

    // You can setup a UIButton here for your "...Read more" action 

    } 

希望,這可以幫助你....