How do I get word wrap information with the new iOS 7 APIs?

后端 未结 2 1677
無奈伤痛
無奈伤痛 2020-12-01 17:48

I noticed that iOS 7 introduces new classes related to text layout such as NSLayoutManager, NSTextStorage, and NSTextContainer. How can I use these in order to get informati

相关标签:
2条回答
  • 2020-12-01 18:01

    swift translation:

        guard let font1: UIFont = textView.font else { return }
        var lines: [String] = []
    
        let maxWidth: CGFloat = textView.frame.width
        let s: NSAttributedString = NSAttributedString.init(string: textView.text, attributes: [.font: font1])
        let tc: NSTextContainer = NSTextContainer.init(size: CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude))
        let lm: NSLayoutManager = NSLayoutManager.init()
        let tm: NSTextStorage = NSTextStorage.init(attributedString: s)
        tm.addLayoutManager(lm)
        lm.addTextContainer(tc)
        lm.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: lm.numberOfGlyphs)) { (rect: CGRect, usedRect: CGRect, textContainer: NSTextContainer, glyphRange: NSRange, Bool) in
    
            let r: NSRange = lm.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
    
            let str = s as NSAttributedString
    
            let s2 = str.attributedSubstring(from: r)
    
            print(s2)
    
            lines.append(s2.string)
    
        }
    
    0 讨论(0)
  • 2020-12-01 18:18

    Example:

    CGFloat maxWidth = 150;
    NSAttributedString *s = 
        [[NSAttributedString alloc] 
            initWithString:@"The quick brown fox jumped over the lazy dog." 
            attributes:@{NSFontAttributeName:[UIFont fontWithName:@"GillSans" size:20]}];
    NSTextContainer* tc = 
        [[NSTextContainer alloc] initWithSize:CGSizeMake(maxWidth,CGFLOAT_MAX)];
    NSLayoutManager* lm = [NSLayoutManager new];
    NSTextStorage* tm = [[NSTextStorage alloc] initWithAttributedString:s];
    [tm addLayoutManager:lm];
    [lm addTextContainer:tc];
    [lm enumerateLineFragmentsForGlyphRange:NSMakeRange(0,lm.numberOfGlyphs) 
        usingBlock:^(CGRect rect, CGRect usedRect, 
                     NSTextContainer *textContainer, 
                     NSRange glyphRange, BOOL *stop) {
        NSRange r = [lm characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
        NSLog(@"%@", [s.string substringWithRange:r]);
    }];
    
    0 讨论(0)
提交回复
热议问题