2015-04-22 91 views
0

我有一個textView,我需要的行數,或sizeToFit成爲sizeToFit之前。我試着在textView中檢查換行符「\ n」的數量。然而,textView中的文本已被解析bc這是非常混亂來自服務器與大量的HTML代碼和可怕的換行符,我必須使用replaceOccurence「\ n」刪除換行符,使文本成爲一個好段落。獲取行數UITextView而不使用「 n」?

var rawString = self.selectedProduct.description 
var cleanString = rawString?.stringByReplacingOccurrencesOfString("\n", withString: " ", options: NSStringCompareOptions.LiteralSearch, range: nil) 

這段代碼當然只會在上面的代碼後返回1。

let desString = self.descriptionTextView.text 
let numLines = desString.componentsSeparatedByString("\n") 
println(numLines.count) 

此代碼崩潰。

let numLines = self.descriptionTextView.contentSize.height/self.descriptionTextView.font.leading 

最終,我想部分顯示文本,並有一個顯示所有文本的按鈕。

感謝

+0

numLines = textView.contentSize.height/textView.font.lineHeight 檢查它plz – aBilal17

+0

你也可以檢查它。 UIFont * font = [UIFont boldSystemFontOfSize:11.0]; CGSize size = [string sizeWithFont:font constrainedToSize:myUITextView.frame.size lineBreakMode:UILineBreakModeWordWrap]; //默認模式 float numberOfLines = size.height/font.lineHeight; – aBilal17

+0

有趣。你的第一個解決方案會崩潰,發現「無解包可選值」錯誤......它每次都會給出一個3.0XX的小數。我很快就用第二種解決方案很難。 –

回答

5

我已經轉換@ aBilal17的評論對非貶值的東西,迅速。

// This gives you the size of that string 

let font = UIFont.systemFontOfSize(11) 
let style = NSMutableParagraphStyle() 
style.lineBreakMode = NSLineBreakMode.ByWordWrapping 
let size = someString.sizeWithAttributes([NSFontAttributeName: font, NSParagraphStyleAttributeName: style]) 

我使用這個擴展我做得到一個字符串的大小限制爲width:

extension String { 
    func sizeForWidth(width: CGFloat, font: UIFont) -> CGSize { 
     let attr = [NSFontAttributeName: font] 
     let height = NSString(string: self).boundingRectWithSize(CGSize(width: width, height: CGFloat.max), options:.UsesLineFragmentOrigin, attributes: attr, context: nil).height 
     return CGSize(width, ceil(height)) 
    } 
} 

所以你的情況,你可以這樣做:

let numLines = desString.sizeForWidth(descriptionTextView.contentSize.width, font: descriptionTextView.font).height/descriptionTextView.font.lineHeight 
+0

謝謝!但我得到「無法分配到LineBreakMode風格」錯誤。當我註釋掉style.lineBreakMode = NSLineBreakMode.ByWordWrapping時,我的size.height每次等於13.123,不管我有多少文本。 –

+0

看到我的更新鄰接:) – Arbitur

+0

仍然是相同的結果。 13.123 .. –