2017-12-11 7 views
1

내 레이블에 속성있는 텍스트를 이와 같이 설정했습니다.iOS UILabel에서 첫 번째 속성으로 된 줄 가져 오기

self.lblContent.attributedText = .......; 

나는 내 라벨의 너비와 높이도 알고 있습니다. 해당 레이블에서 첫 줄을 가져와야하며 속성이있는 형식이어야합니다. 어떻게받을 수 있습니까?

+1

이 도움이 될 수 https://stackoverflow.com/a/14413484/5807290 –

답변

1

스위프트 3

let arrayLines = getLinesArrayFromLabel(label: lbl) 
print(arrayLines[0]) 

func getLinesArrayFromLabel(label:UILabel) -> [String] { 

     let text:NSString = label.text! as NSString // TODO: Make safe? 
     let font:UIFont = label.font 
     let rect:CGRect = label.frame 

     let myFont:CTFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil) 
     let attStr:NSMutableAttributedString = NSMutableAttributedString(string: text as String) 
     attStr.addAttribute(String(kCTFontAttributeName), value:myFont, range: NSMakeRange(0, attStr.length)) 
     let frameSetter:CTFramesetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString) 
     let path:CGMutablePath = CGMutablePath() 
     path.addRect(CGRect(x:0, y:0, width:rect.size.width, height:100000)) 

     let frame:CTFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil) 
     let lines = CTFrameGetLines(frame) as NSArray 
     var linesArray = [String]() 

     for line in lines { 
      let lineRange = CTLineGetStringRange(line as! CTLine) 
      let range:NSRange = NSMakeRange(lineRange.location, lineRange.length) 
      let lineString = text.substring(with: range) 
      linesArray.append(lineString as String) 
     } 
     return linesArray 
} 

NSAttributedString은

func getLinesArrayOfStringInLabel(label:UILabel) -> [NSAttributedString] { 

    let text:NSAttributedString = label.attributedText! // TODO: Make safe? 
    let font:UIFont = label.font 
    let rect:CGRect = label.frame 

    let myFont:CTFont = CTFontCreateWithName(font.fontName as CFString, font.pointSize, nil) 
    let attStr:NSMutableAttributedString = NSMutableAttributedString(attributedString: text) 
    attStr.addAttribute(String(kCTFontAttributeName), value:myFont, range: NSMakeRange(0, attStr.length)) 
    let frameSetter:CTFramesetter = CTFramesetterCreateWithAttributedString(attStr as CFAttributedString) 
    let path:CGMutablePath = CGMutablePath() 
    path.addRect(CGRect(x:0, y:0, width:rect.size.width, height:100000)) 

    let frame:CTFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil) 
    let lines = CTFrameGetLines(frame) as NSArray 
    var linesArray = [NSAttributedString]() 

    for line in lines { 
     let lineRange = CTLineGetStringRange(line as! CTLine) 
     let range:NSRange = NSMakeRange(lineRange.location, lineRange.length) 
     let lineString = text.attributedSubstring(from: range) 
     linesArray.append(lineString) 
    } 
    return linesArray 
} 
+0

ahh..it 나에게 문자열을 제공합니다. attributedString이 필요합니다. –

+0

내가 원인 문자열로 시도하자 –

+0

@KhantThuLinn 두 번째 방법을 시도해보십시오. 작동 매력 –

관련 문제