- 根據我們的開發需求, 有時候UITextField不足以滿足我們, 比如多行輸入時, 不得不使用新的控件.
- 本篇文章對UITextView進行了重寫和封裝, 希望可以幫助大家.
重新定義封裝UITextView
使用方法
常見問題
注意: PlaceHolderTextView為作者所起的名字, 可以随便叫什麼
UITextView重寫封裝
/* .h檔案 */
#import <UIKit/UIKit.h>
@interface PlaceHolderTextView : UITextView
@property (nonatomic, strong) NSString *placeholder; /* 灰色提示文字, 用于外部調用時添加的占位字元 */
@end
/* .m檔案 */
#import "PlaceHolderTextView.h"
@implementation PlaceHolderTextView
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
[self awakeFromNib];
}
return self;
}
- (void)awakeFromNib {
[self addObserver];
}
#pragma mark 注冊通知
- (void)addObserver {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidBeginEditing:) name:UITextViewTextDidBeginEditingNotification object:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidEndEditing:) name:UITextViewTextDidEndEditingNotification object:self];
}
#pragma mark 移除通知
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark 開始編輯
- (void)textDidBeginEditing:(NSNotification *)notification {
if ([super.text isEqualToString:_placeholder]) {
super.text = @"";
[super setTextColor:[UIColor blackColor]];
}
}
#pragma mark 結束編輯
- (void)textDidEndEditing:(NSNotification *)notification {
if (super.text.length == ) {
super.text = _placeholder;
/* 如果文本框内是原本的提示文字,則顯示灰色字型 */
[super setTextColor:[UIColor lightGrayColor]];
}
}
#pragma mark 重寫setPlaceholder方法
- (void)setPlaceholder:(NSString *)aPlaceholder {
_placeholder = aPlaceholder;
[self textDidEndEditing:nil];
}
#pragma mark 重寫getText方法
- (NSString *)text {
NSString *text = [super text];
if ([text isEqualToString:_placeholder]) {
return @"";
}
return text;
}
@end
使用
self.feedBackTextView = [[PlaceHolderTextView alloc] initWithFrame:CGRectMake(, , , )]; /* 給出尺寸 */
[self.view addSubview:self.feedBackTextView];
[self.feedBackTextView mas_remakeConstraints:^(MASConstraintMaker *make) {
make.centerX.equalTo(self.view);
make.top.equalTo(self.view.mas_top).with.offset();
make.width.equalTo(@355);
make.height.equalTo(@150);
}];/* 添加限制 */
self.feedBackTextView.placeholder = @"親, 您遇到什麼系統問題啦, 或者有什麼功能建議嗎? 歡迎提給我們, 謝謝!"; /* 添加占位字元和TextField的placeholder 一樣的使用方式 */
/* 如果需要圓角和邊框這裡設定 */
self.feedBackTextView.layer.borderWidth = ;
self.feedBackTextView.layer.borderColor = [UIColor grayColor].CGColor;
/* 設定圓角 */
self.feedBackTextView.layer.cornerRadius = ;
self.feedBackTextView.font = [UIFont systemFontOfSize:];
常見問題
比較常見的就是使用時 輸入的文字居中顯示 不像别人APP 中的靠上顯示。
/* 關閉視圖的自适應就可以了 */
self.automaticallyAdjustsScrollViewInsets = NO;