开发者

UITextView - modifying selected text

开发者 https://www.devze.com 2023-03-18 16:20 出处:网络
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 f

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?


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:-

  • First take a scrollview and add a label or another textview with different style as you want with bold font or chagne color and add as subview in scrollview.
  • For textviews added in scrollview, you should take a frame of that textview as larger as text or lines in textview for stop scrolling in textview because we already added textview in scrollview for better look.
  • So,Take as many textviews or labels or images as your need and add then to the scrollview things are very simple you can do this using an Interface builder. Just need to define a perfect content size for scrollview depends on subviews you have.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号