帶PlaceHolder的UITextView
在日常開發中,用戶反饋界面基本在每個App中都存在,如下圖所示:
屏幕快照 2017-05-12 下午3.58.11.png
輸入反饋建議的地方通常都是一個UITextView,但是比較蛋疼的地方就是UITextView并沒有PlaceHolder屬性。在這里,肯定有很多方式可以解決這個問題。我這里把我通常是在
- (void)textViewDidBeginEditing:(UITextView *)textView
和- (void)textViewDidEndEditing:(UITextView *)textView
這兩個代理中去做處理。其實也很簡單。
代碼如下:
- (UITextView *)textView {
if (!_textView) {
_textView = [[UITextView alloc] init];
_textView.backgroundColor = [UIColor whiteColor];
_textView.delegate = self;
_textView.text = @"請輸入遇到的問題或建議";
// 設置PlaceHolder的字體顏色
_textView.textColor = [UIColor xk_colorWithHexString:@"#CCCCD1"];
// 設置字體(里面的宏和常量是我項目中自己定義的)
_textView.font = FONT(xkfontSize * PROPORTION);
}
return _textView;
}
- (void)textViewDidBeginEditing:(UITextView *)textView {
// 在已經開始編輯的方法中判斷如果當前textView.text為PlaceHolder的值 就將其值改變為空字符串
if ([textView.text isEqualToString:@"請輸入遇到的問題或建議"]) {
textView.text = @"";
}
textView.textColor = [UIColor xk_colorWithHexString:kBTitleColor];
}
- (void)textViewDidEndEditing:(UITextView *)textView {
// 在結束編輯的時候去判斷 如果沒有輸入文字 那么重新將PlaceHolder設置上,同時將text的顏色修改回來
if ([NSString isEmpty:textView.text]) {
textView.text = @"請輸入遇到的問題或建議";
textView.textColor = [UIColor xk_colorWithHexString:@"#CCCCD1"];
}
}
這樣,我們就簡單的實現了一個帶PlaceHolder的UITextView的。
效果圖.gif