简体   繁体   中英

How to Get NSAttributedString from CGSIZE for UITextView?

I am creating a reader app using UITextView and NSAttributedString , I need to split whole attributedString into smaller amount of attributed string to enable Pages Concept.

I have method for calculating frame size of given attributed string.

        CGRect rect = [attrString boundingRectWithSize:CGSizeMake(768, 10000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];

But I need to get attributeString for (768, 1024) ContentSize.

I have used this, but the attributedStrings are not correctly divided, because it contains NSTextAttachment and HTML stings.

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)delegate.attributedString);

How can I calculated this? and It need to be fast and need to takes small amount of memory.

If you want to know the size of a UITextView you should not ask the bounding rect of text, because it is not the size of the view. UITextView contains padding and you need to take into account that.
The best and easier way, is to call sizeToFit on the text view right after you added the text. Later just ask for the UItextView frame.

你可以使用UITextView函数sizeThatFits:

[textView sizeThatFits:CGSizeMake(768, 1024)]

If you want to split text between « pages », then you need to use the capabilities of the NSLayoutManager and the NSTextContainer classes. Basically, you need to create a NSTextContainer instance for every page you wish to display, using the initWithSize: initializer. Then you register those containers using -[NSLayoutManager addTextContainer:] .

Here is the relevant documentation : https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html#//apple_ref/doc/uid/TP40009542-CH4-SW35

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM