I have a UITextView and i want to select a certain part of this text and modify its style. Like changing the color, making it italic or bold, increasing the font size, or changing the font family.
Any Help?
I have a UITextView and i want to select a certain part of this text and modify its style. Like changing the color, making it italic or bold, increasing the font size, or changing the font family.
Any Help?
You should use shouldChangeTextInRange
. This is because you need range to locate the position where you want the text changed.
UITextView lets you save your style in textView.attributedString
.
The solution is to get textView's Attributed String and replace the desired sub string in it with changed or styled text.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
NSMutableAttributedString *textViewText = [[NSMutableAttributedString alloc]initWithAttributedString:textView.attributedText]; //gets textView style string
NSRange selectedTextRange = [textView selectedRange];
NSString *selectedString = [textView textInRange:textView.selectedTextRange]; //our selected text
//lets say you always want to make selected text bold
UIFont *boldFont = [UIFont boldSystemFontOfSize:self.txtNote.font.pointSize];
NSDictionary *boldAttr = [NSDictionary dictionaryWithObject:boldFont forKey:NSFontAttributeName];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:selectedString attributes:boldAttr]; //make attributed string of our selectedtext
[textViewText replaceCharactersInRange:range withAttributedString:attributedText]; // replace
textView.attributedText = textViewText;
return false;
}
Yes. Wait for iOS 5. I think most of the info about iOS 5 is still under NDA, so we can't discuss it here.
Or develop it all yourself with CoreText.
You can use some alternative things as follows:-