前些天看了白胡子老头的关于textview的视频,今天尝试做了个demo. 效果图如下:
--------------------->
实现代码如下:
- (IBAction)ChangeColor:(UIButton *)sender
{
UIColor *selectTextColor = sender.backgroundColor;
[self ChangeTextColor:selectTextColor inView:self.TextView];
}
-(void)ChangeTextColor:(UIColor *)color inView:(UITextView *)textView
{
NSRange textRange = textView.selectedRange;
[self.TextView.textStorage addAttribute:NSForegroundColorAttributeName value:color range:textRange];
}
1. textStorage: @property(nonatomic, readonly, retain) NSTextStorage *textStorage,由于NSTextStorage继承与NSMutableAttributedString,故可以直接用addAttribute方法。
textview的其他属性(text,attributedtext)都不能直接调用该方法。
2.ChangeColor:可以将四个按钮的Action都关联到该方法上(一开始采用4个按钮,4个函数,确实冗余了些)。
3.selecteRange:这个属性在textview中用的会比较多,网上常用的一个例子是建立光标的首位置,如下所示:
textview.selectedRange = NSMakeRange(0,0);
textview.selectedRange = NSMakeRange(textview.text.length,0)
4.auto layout: 底层的四个按钮通过auto layout的方式去布局.