2014-12-29 24 views
2

我有一個UILabel,其文本通過-setAttributedText: 動態設置。NSAttributedString包含各種動態屬性,即不同字體或不同範圍的字符。 UILabel的寬度受到限制(通過自動佈局),高度可變(numberOfLines = 0)。具有固定寬度和NSAttributedString的UILabel的渲染線數

我需要確定的是在給定NSAttributedString和width約束條件下呈現的文本行數。

請注意,我不在尋找標籤的高度,我正在尋找渲染線條的數量。另請注意,我無法執行基於font.lineHeight的任何計算,因爲字體在整個NSAttributedString中都不相同。

對於一些背景,對於有兩行或更多行的標籤,對於有1行的標籤和label.textAlignment=NSTextAlignmentLeft,設置label.textAlignment=NSTextAlignmentCenter。在自動佈局和UILabel完成其業務之後,我會在-[UIViewController viewDidLayoutSubviews]中執行此操作。或者也許有更簡單的方法來實現相同的目標。

回答

0

從技術上講,這並不回答如何學習渲染文本行數的問題,但我確實找到了解決方案,所以我想我會發布它。

我最終做的是去除標籤上的寬度自動佈局約束(實際上是超級視圖的前後約束),並在容器約束中水平添加了一箇中心。然後在-[UIViewController viewDidLayoutSubviews]我設置label.preferredMaxLayoutWidth=self.view.frame.size.width-margin。標籤的textAlignment=NSTextAlignmentLeft

如果僅有一行,則標籤居中的效果相同,如果是兩個或更多,則實現左對齊的效果。

-2

你可以NSMutableAttributedString這樣設置你的UILabel

UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)]; 
[contentLabel setLineBreakMode:NSLineBreakByWordWrapping]; 
[contentLabel setNumberOfLines:0]; 
[contentLabel setFont:[UIFont systemFontOfSize:13]; 

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello I am a long sentence that should break over multiple lines"]; 
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(0, [string length])]; 

contentLabel.attributedText = string; 

希望這有助於...

0

這是斯威夫特3版

extension NSAttributedString { 

    func numberOfLines(with width: CGFloat) -> Int { 

     let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))) 
     let frameSetterRef : CTFramesetter = CTFramesetterCreateWithAttributedString(self as CFAttributedString) 
     let frameRef: CTFrame = CTFramesetterCreateFrame(frameSetterRef, CFRangeMake(0, 0), path.cgPath, nil) 

     let linesNS: NSArray = CTFrameGetLines(frameRef) 

     guard let lines = linesNS as? [CTLine] else { return 0 } 
     return lines.count 
    } 
} 

希望這有助於

+1

提供某種解釋會幫助別人理解。 –

相關問題