自定義TextView與其他人的不同點(diǎn)
在做自定義textView時(shí)独旷,我發(fā)現(xiàn)很多人是使用boundingRectWithSize來計(jì)算textView的text的高度逝薪,從而更新textView的高度丢郊。其實(shí)這種做法是多余的曼月。UITextView本身就是繼承自UIScrollView的容达,所以UITextView本身是有一個(gè)contentSize的屬性的。每當(dāng)UITextView的高度發(fā)生變化冰沙,UITextView的contentSize屬性的height就會發(fā)生變化侨艾,所以我根據(jù)這一點(diǎn),使用KVO監(jiān)聽contentSize屬性即可獲得textView的最新高度拓挥。本文自定義的textView使用場景:UITableViewCell里自動計(jì)算行高的textView唠梨。
主要代碼:
// KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"contentSize"]) {
[self configureTextViewFrame];
}
}
// 計(jì)算textView的frame
- (void)configureTextViewFrame {
// self的frame是初始化時(shí)定的,默認(rèn)是父視圖的高度
// 只有當(dāng)contentSize的高度小于self的高度時(shí)才需要計(jì)算高度侥啤,超出則不計(jì)算
if (self.textView.contentSize.height < self.bounds.size.height) {
CGRect rect = self.bounds;
// textView擴(kuò)展方向:向兩邊(默認(rèn))当叭;向下;向上
switch (self.extendDirection) {
case YSTextViewExtendDirectionBothsides:
rect.origin.y = (rect.size.height - self.textView.contentSize.height) / 2.f;
break;
case YSTextViewExtendDirectionUpside:
rect.origin.y = rect.size.height - self.textView.contentSize.height;
break;
case YSTextViewExtendDirectionDownside:
rect.origin.y = 0;
break;
}
rect.size.height = self.textView.contentSize.height;
self.textView.frame = rect;
} else {
self.textView.frame = self.bounds;
self.isExtending = NO;
}
CGRect textBounds = self.textView.bounds;
textBounds.origin.x += 5.f;
self.placeholderLabel.frame = textBounds;
}
調(diào)用示例:
// contentView模擬UITableViewCell的contentView
UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(100, 200, 200, 100)];
[self.view addSubview:contentView];
contentView.backgroundColor = [UIColor lightGrayColor];
YSExtendTextView *textView = [YSExtendTextView new];
textView.frame = CGRectMake(15, 5, 170, 90);
textView.extendDirection = YSTextViewExtendDirectionDownside;// 輸入框延伸方向(默認(rèn)是從中間向兩邊)
textView.placeholder = @"請輸入文字~";
[contentView addSubview:textView];
喜歡該控件的朋友可以從github下載使用盖灸。
GitHub