一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

ios开发之UITextView实现首行文字缩进和默认文字例子

时间:2016-05-15 编辑:简简单单 来源:一聚教程网


在使用UITextView时可能会遇到各种各样的效果,例如在UITextView首行前面有提示文字,并且后面输入的内容在提示的文字后面,在输入之前有默认的文字,输入过程中默认的文字会消失隐藏,具体实现代码如下:

#import "UItextviewSuoJinViewController.h"
 
@interface UItextviewSuoJinViewController (){
    //意见内容
    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.maximumLine;   /**最大行高*/
    paragraphStyle.firstLineHeadIndent = 93.f;    /**首行缩进宽度*/
    paragraphStyle.alignment = NSTextAlignmentJustified;
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:13],
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
}

可以将代码拷到自己的工程文件中实现看看效果。

热门栏目