在使用UITextView時可能會遇到各種各樣的效果,例如在UITextView首行前面有提示文字,並且後面輸入的內容在提示的文字後面,在輸入之前有默認的文字,輸入過程中默認的文字會消失隱藏,具體實現代碼如下:
#import "UItextviewSuoJinViewController.h"
@interface UItextviewSuoJinViewController ()<UITextViewDelegate>{
//意見內容
UITextView *contentTextView;
//在UITextView上面覆蓋個UILable
UILabel *promptLabel;
}
@end
@implementation UItextviewSuoJinViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
//意見內容
contentTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, kHeaderHeight, kScreenWidth, 86)];
contentTextView.font = FONT(13);
contentTextView.delegate = self;
[self.view addSubview:contentTextView];
UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(14, 0, 60, 35)];
contentLabel.font = FONT(13);
contentLabel.text = @"*您的意見";
[contentTextView addSubview:contentLabel];
//在UITextView上面覆蓋個UILable
promptLabel = [[UILabel alloc] init];
promptLabel.frame =CGRectMake(5,5,200,25);
promptLabel.text = @" 請輸入意見";
promptLabel.enabled = NO;
promptLabel.backgroundColor = [UIColor clearColor];
promptLabel.font = [UIFont systemFontOfSize:13];
promptLabel.textColor = RGB(245, 245, 245);
[contentTextView addSubview:promptLabel];
//改變五角星的顏色
NSMutableAttributedString *contentStr = [[NSMutableAttributedString alloc] initWithString:contentLabel.text];
[contentStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 1)];
contentLabel.attributedText = contentStr;
}
#pragma mark -UITextView的代理方法
-(void)textViewDidChange:(UITextView *)textView{
if (textView.text.length == 0) {
promptLabel.hidden = NO;
}else{
promptLabel.hidden = YES;
}
//首行縮進
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 3; //行間距
// paragraphStyle.maximumLineHeight = 60; /**最大行高*/
paragraphStyle.firstLineHeadIndent = 93.f; /**首行縮進寬度*/
paragraphStyle.alignment = NSTextAlignmentJustified;
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:13],
NSParagraphStyleAttributeName:paragraphStyle
};
textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
}
可以將代碼拷到自己的工程文件中實現看看效果。