为输入框添加 Placeholder 效果

实现思路

为输入框添加一个 UILabel,实现 Placeholder 效果,做好 UI 方面的处理。

实现步骤

1.会话页面添加 UILabel 属性

@property(nonatomic, strong) UILabel *placeholderLabel;

2.配置第一步中的 UILabel 对象

- (void)configPlaceholder {    
    //初始化和设置    
    self.placeholderLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 180, 20)];
    [self.chatSessionInputBarControl.inputTextView addSubview:self.placeholderLabel];
    NSString *draft = self.chatSessionInputBarControl.draft;    
    self.placeholderLabel.text = @"测试 Placeholder";    
    if (draft.length > 0) {        
        self.placeholderLabel.hidden = YES;    
    } else {        
        self.placeholderLabel.hidden = NO;    
        }  
    self.placeholderLabel.textColor = [UIColor grayColor];    
    self.placeholderLabel.userInteractionEnabled = YES;    
    //添加点击手势    
    UITapGestureRecognizer *tapLabel = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapPlaceholderLabel)];    
    [self.placeholderLabel addGestureRecognizer:tapLabel];
}
    
- (void)tapPlaceholderLabel {    
    [self.chatSessionInputBarControl updateStatus:KBottomBarKeyboardStatus animated:YES];
}

3.在内容发生变化和点击发送后,设置 placeholder 效果的显示

- (void)inputTextView:(UITextView *)inputTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {    
//在内容发生变化和点击发送后,设置 placeholder 效果的显示    
if ((range.location == 0 && [text isEqualToString:@""]) || [text isEqualToString:@"\n"]) {        
    self.placeholderLabel.hidden = NO;    
    } else {        
    self.placeholderLabel.hidden = YES;    
    }
}

4.当撤回消息,点击“重新编辑”后,关闭 placeholder 效果的显示

- (void)didTapReedit:(RCMessageModel *)model {    
    self.placeholderLabel.hidden = YES;    
    [super didTapReedit:model];
}

效果图:

![屏幕快照 2020-05-21 上午10.34.53.png](https://rongcloud-res.cn.ronghub.com/2ddb31191b2f3a68a8778c24d8a060ab.png?attname=屏幕快照 2020-05-21 上午10.34.53.png “2ddb31191b2f3a68a8778c24d8a060ab.png”)