自定义UITextView实现占位文字,设置最大高度,设置最大文

2017-05-12  本文已影响34人  漫步在银河畔

直接上代码

import <UIKit/UIKit.h>

define TEXTCOUNT @"TEXTCOUNT"

@interface EditTextView : UITextView

@property(nonatomic,strong)NSString * placeHolder; //占位文字
@property(nonatomic,strong)UIColor * textEditColor; //设置文本颜色
@property(nonatomic,strong)UIFont * fontEdit; //字体

@property(nonatomic, assign)CGFloat maxHeight; //textView最大高度设置,如果有,就设置,否则高度随着文字高度变化而变化

@property(nonatomic, assign)NSInteger textMaxCount; //设置最大输入文本个数

@property(nonatomic, assign)NSInteger textCount; //已经输入的文本个数,通过通知来获取

@end

import "EditTextView.h"

@interface EditTextView ()<UITextViewDelegate>

@property(nonatomic, assign)CGFloat width;

@property(nonatomic, assign)CGFloat height;

@end

@implementation EditTextView

//====================此处对输入字数限制
UITextRange *selectedRange = [self markedTextRange];
UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];

// 没有高亮选择的字,则对已输入的文字进行字数统计和限制,防止中文被截断
if (!position){
    if (self.textMaxCount&& textString.length > self.textMaxCount){
        NSRange rangeRange = [textString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, self.textMaxCount)];
        self.text = [textString substringWithRange:rangeRange];
    }
}

// 此处限制高度
CGRect rect = [textString boundingRectWithSize:CGSizeMake(self.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.fontEdit,NSForegroundColorAttributeName:self.textEditColor} context:nil];

CGRect newFrame = self.frame;
if (rect.size.height> self.height) {
    // 如果外部设置了固定高度
    if (self.maxHeight && rect.size.height> self.maxHeight) {
        newFrame.size = CGSizeMake(self.width, self.maxHeight);
    }else{
        newFrame.size = CGSizeMake(self.width, rect.size.height);
    }
}else{
    
    newFrame.size = CGSizeMake(self.width, self.height);
}


self.frame = newFrame;
self.textCount = self.text.length;
//发送通知,计算文本字数
[[NSNotificationCenter defaultCenter] postNotificationName:TEXTCOUNT object:@(self.textCount)];

}

//获取文本时,一定要排除占位符的情况

@end

上一篇下一篇

猜你喜欢

热点阅读