這是效果,輸入框根據(jù)內(nèi)容多少自動(dòng)伸縮大小。
關(guān)于輸入框遮擋鍵盤(pán)的處理在另外一篇文章描述。
1、繼承UITextView
UITextField只能輸入一行,要輸入多行文本,那么只能用UITextView,如下所示,KTAutoHeightTextView繼承自UITextView,然后使用自動(dòng)布局添加三個(gè)高度上的約束,并連線(xiàn):
這里heightConstraint是用來(lái)控制實(shí)際textView的高度的,maxHeightConstraint和minHeightConstraint則分別用來(lái)控制最大和最小的高度。
2、IB_DESIGNABLE和IBInspectable的實(shí)時(shí)預(yù)覽
除此之外,還定義了2個(gè)屬性showsRoundCorner和placeholder,注意到開(kāi)頭有個(gè)IB_DESIGNABLE,這兩個(gè)屬性前面的還多出來(lái)了IBInspectable,IB_DESIGNABLE配合IBInspectable的作用就是在storyboard或者xib中實(shí)時(shí)更新屬性效果的。有了這兩個(gè)東西,會(huì)發(fā)現(xiàn)KTAutoHeightTextView的屬性檢查器中會(huì)多出兩個(gè)屬性:
僅僅用IB_DESIGNABLE和IBInspectable還不足以達(dá)到實(shí)時(shí)在storyboard或者xib中預(yù)覽圓角和placeholder的效果,還要在相應(yīng)的屬性setter中加上更新的代碼,比如showsRoundCorner屬性的setter:
- (void)setShowsRoundCorner:(BOOL)showsRoundCorner
{
_showsRoundCorner = showsRoundCorner;
if (showsRoundCorner)
{
self.layer.masksToBounds = YES;
self.layer.cornerRadius = 5.0;
self.layer.borderColor = [[UIColor lightGrayColor] CGColor];
self.layer.borderWidth = 0.5;
}
else
{
self.layer.masksToBounds = NO;
self.layer.cornerRadius = 0.0;
self.layer.borderColor = [[UIColor clearColor] CGColor];
self.layer.borderWidth = 0.0;
}
}
在storyboard中設(shè)置“Shows RoundCorner”為On,那么就會(huì)看到預(yù)覽的圓角效果了:
3、placeholder實(shí)現(xiàn)
同樣實(shí)現(xiàn)placeholder的setter:
- (void)setPlaceholder:(NSString *)placeholder
{
_placeholder = [placeholder copy];
[self setNeedsDisplay];
}
#pragma mark - Drawing
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
if ([self.text length] == 0 && self.placeholder) {
[[UIColor lightGrayColor] set];
[self.placeholder drawInRect:CGRectInset(rect, 6.0f, 8.0f) withAttributes:[self kt_placeholderTextAttributes]];
}
}
#pragma mark - Utilities
- (NSDictionary *)kt_placeholderTextAttributes
{
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
paragraphStyle.alignment = self.textAlignment;
return @{ NSFontAttributeName : self.font,
NSForegroundColorAttributeName : [UIColor lightGrayColor],
NSParagraphStyleAttributeName : paragraphStyle };
}
這里在setter里面調(diào)用setNeedsDisplay方法,該方法調(diào)用之后,drawRect方法會(huì)被調(diào)用,然后在這里面加上繪制placeholder文本的邏輯。
4、自動(dòng)高度變化的實(shí)現(xiàn)
這里的實(shí)現(xiàn)思路是監(jiān)聽(tīng)文本編輯,文本變化的通知,然后調(diào)用setNeedsDisplay,注意setNeedsDisplay不光會(huì)導(dǎo)致drawRect方法被觸發(fā),還會(huì)導(dǎo)致layoutSubviews方法被觸發(fā)來(lái)進(jìn)行重布局,因此在layoutSubviews方法里面寫(xiě)上更新高度的邏輯,代碼很簡(jiǎn)單:
- (void)awakeFromNib
{
[super awakeFromNib];
[self addTextViewNotificationObservers];
}
- (void)dealloc
{
[self removeTextViewNotificationObservers];
}
- (void)layoutSubviews
{
[super layoutSubviews];
// calculate size needed for the text to be visible without scrolling
CGSize sizeThatFits = [self sizeThatFits:self.frame.size];
float newHeight = sizeThatFits.height;
// if there is any minimal height constraint set, make sure we consider that
if (self.maxHeightConstraint) {
newHeight = MIN(newHeight, self.maxHeightConstraint.constant);
}
// if there is any maximal height constraint set, make sure we consider that
if (self.minHeightConstraint) {
newHeight = MAX(newHeight, self.minHeightConstraint.constant);
}
// update the height constraint
self.heightConstraint.constant = newHeight;
}
#pragma mark -- notifications
- (void)addTextViewNotificationObservers
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(kt_didReceiveTextViewNotification:)
name:UITextViewTextDidChangeNotification
object:self];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(kt_didReceiveTextViewNotification:)
name:UITextViewTextDidBeginEditingNotification
object:self];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(kt_didReceiveTextViewNotification:)
name:UITextViewTextDidEndEditingNotification
object:self];
}
- (void)removeTextViewNotificationObservers
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UITextViewTextDidChangeNotification
object:self];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UITextViewTextDidBeginEditingNotification
object:self];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UITextViewTextDidEndEditingNotification
object:self];
}
- (void)kt_didReceiveTextViewNotification:(NSNotification *)notification
{
[self setNeedsDisplay];
}
代碼是在利用sizeThatFits在contentSize變化的時(shí)候去計(jì)算合適的大小fitHeight,同時(shí)利用一定的規(guī)則在合適的時(shí)候?qū)ふ腋叨燃s束heightConstraint。當(dāng)存在heightConstraint的時(shí)候修改約束值,不存在的時(shí)候直接修改bounds,從而實(shí)現(xiàn)在自動(dòng)布局或者非自動(dòng)布局情況下都能自動(dòng)匹配高度。
5、重寫(xiě)屬性的setter
重寫(xiě)屬性的setter,保證實(shí)時(shí)更新。注意setBounds的setter,是為了避免出現(xiàn)錯(cuò)誤contentOffset的情況。
#pragma mark -- 重寫(xiě)系統(tǒng)的setter --
- (void)setBounds:(CGRect)bounds
{
[super setBounds:bounds];
if (self.contentSize.height <= self.bounds.size.height + 1){
self.contentOffset = CGPointZero; // Fix wrong contentOffset
}
}
- (void)setText:(NSString *)text
{
[super setText:text];
[self setNeedsDisplay];
}
- (void)setAttributedText:(NSAttributedString *)attributedText
{
[super setAttributedText:attributedText];
[self setNeedsDisplay];
}
- (void)setFont:(UIFont *)font
{
[super setFont:font];
[self setNeedsDisplay];
}
- (void)setTextAlignment:(NSTextAlignment)textAlignment
{
[super setTextAlignment:textAlignment];
[self setNeedsDisplay];
}
完整的項(xiàng)目https://github.com/tujinqiu/KTAutoHeightTextView