iOS给TextView 添加占位符

最近比较繁忙,但也不能荒废了,所以更新点小技巧
TextView是没有自带的占位符的,咱们自己写.
思路,利用一个全局的label,他的透明与否是仿制占位符的技巧.直接上代码,略简单

@interface ViewController ()<UITextViewDelegate>
@property (nonatomic, strong)UILabel *lb;

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    UITextView *tv = [[UITextView alloc] initWithFrame:CGRectMake(10, 100, 300, 200)];
    tv.delegate = self;
    tv.backgroundColor = [UIColor redColor];
    self.lb = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 50)];
    self.lb.text = @"我是占位符";
    self.lb.enabled = NO;
    self.lb.backgroundColor = [UIColor greenColor];
    [tv addSubview:self.lb];
    [self.view addSubview:tv];
}

重要的是下边的协议方法,上边的大家都会

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];//按回车取消第一相应者
    }
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.lb.alpha = 0;//开始编辑时
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{//将要停止编辑(不是第一响应者时)
    if (textView.text.length == 0) {
        self.lb.alpha = 1;
    }
    return YES;
}

如果有两个textview .可用 isFirstResponder .做判断,谁是第一响应者.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容