iOS 開發(fā) 自定義限制輸入字?jǐn)?shù)的UITextView

代碼如下:
HDTextView.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN
@class HDTextView;
@interface HDTextView : UITextView<UITextViewDelegate>

@property (strong, nonatomic) UILabel *placeholderLabel;//占位label
@property (copy, nonatomic) NSString *placeholder; //占位字
@property (assign, nonatomic) NSInteger maxLength;//最大長(zhǎng)度
@property (strong, nonatomic) UILabel *wordNumLabel;//計(jì)算字?jǐn)?shù)label
///是否允許輸入emoji 默認(rèn)不允許
@property (nonatomic, assign) BOOL allowEmoji;

///文字輸入
@property (copy, nonatomic) void(^didChangeText)(HDTextView *textView);

- (void)didChangeText:(void(^)(HDTextView *textView))block;

@end

NS_ASSUME_NONNULL_END

HDTextView.m

#import "HDTextView.h"
@interface HDTextView()
@property (strong, nonatomic) NSString *currentText;

@end
@implementation HDTextView

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self addObserver];
        [self setView];
        //設(shè)置文字偏移量
        self.textContainerInset = UIEdgeInsetsMake(16, 15, 16, 15);
    }
    return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder{
    self = [super initWithCoder:aDecoder];
    
    if (self) {
        [self addObserver];
        [self setView];
        //設(shè)置文字偏移量
        self.textContainerInset = UIEdgeInsetsMake(16, 15, 16, 15);
        
    }
    return self;
}
-(id)init{
    self = [super init];
    if (self) {
        [self addObserver];
        [self setView];
        //設(shè)置文字偏移量
        self.textContainerInset = UIEdgeInsetsMake(16, 15, 16, 15);
    }
    return self;
}
-(void)setView{
    if (!self.placeholderLabel) {
        self.placeholderLabel = [[UILabel alloc]initWithFrame:CGRectMake(16, 16, self.frame.size.width-16, self.frame.size.height)];
        self.placeholderLabel.textColor = [UIColor lightGrayColor];
        self.placeholderLabel.numberOfLines = 0;
        self.placeholderLabel.font = [self font];
        [self addSubview:self.placeholderLabel];
        super.delegate = self;
    }
    
    if (!self.wordNumLabel) {
        
        self.wordNumLabel = [[UILabel alloc]initWithFrame:CGRectZero];
        self.wordNumLabel.font = [UIFont systemFontOfSize:13];
        self.wordNumLabel.textColor = [UIColor lightGrayColor];
        self.wordNumLabel.textAlignment = NSTextAlignmentRight;
        [self addSubview:self.wordNumLabel];
        
        
    }
    
    self.allowEmoji = NO;//不允許輸入emoji
    
}

-(void)layoutSubviews{
    self.placeholderLabel.frame = CGRectMake(16, 16, self.frame.size.width-16, self.frame.size.height);
    [self.placeholderLabel sizeToFit];
    [self.wordNumLabel sizeToFit];
    [self refreshFram];
}
-(void)addObserver
{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UITextViewTextDidChangeNotification object:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(placeholderTextViewdidChange:) name:UITextViewTextDidChangeNotification object:self];
    
    
    
}


-(void)setPlaceholder:(NSString *)placeholder{
    _placeholder = placeholder;
    self.placeholderLabel.text = _placeholder;
    [self.placeholderLabel sizeToFit];
    [self endEditing:NO];
}
-(void)setMaxLength:(NSInteger)maxLength{
    
    _maxLength = maxLength;
    self.wordNumLabel.text = [NSString stringWithFormat:@"0/%ld",(long)_maxLength];
    
}
-(void)placeholderTextViewdidChange:(NSNotification *)notificat{
    
    HDTextView *textView = (HDTextView *)notificat.object;
    if ([self.text length]>0) {
        [self.placeholderLabel setHidden:YES];
    }else{
        [self.placeholderLabel setHidden:NO];
        
    }
    
    if ([textView.text length]>self.maxLength&&self.maxLength!=0&&textView.markedTextRange == nil) {
        
        
        textView.text = [textView.text substringToIndex:self.maxLength];
        
    }
    self.wordNumLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)[textView.text length],(long)_maxLength];
    if (self.didChangeText) {
        self.didChangeText(textView);
    }
    
    [self refreshFram];
    _currentText = textView.text;
    
}


- (void)didChangeText:(void (^)(HDTextView *))block{
    self.didChangeText = block;
}


- (void)setText:(NSString *)text{
    [super setText:text];
    if (text.length>0) {
        [self.placeholderLabel setHidden:YES];
        self.wordNumLabel.text = [NSString stringWithFormat:@"%ld/%ld",(long)[text length],(long)_maxLength];
        [self.wordNumLabel sizeToFit];
        [self refreshFram];
        
    }
}


-(void)placeholderTextViewEndEditing{
    
    if ([self.text length]>0) {
        [self.placeholderLabel setHidden:YES];
    }else{
        [self.placeholderLabel setHidden:NO];
        
    }
}

- (void)refreshFram{
    [self.wordNumLabel sizeToFit];
    if (self.contentSize.height>self.frame.size.height-self.wordNumLabel.frame.size.height-5) {
        self.wordNumLabel.frame = CGRectMake(self.frame.size.width - self.wordNumLabel.frame.size.width-5, self.contentSize.height+self.contentInset.bottom-self.wordNumLabel.frame.size.height-5, self.wordNumLabel.frame.size.width, self.wordNumLabel.frame.size.height);
        self.contentInset = UIEdgeInsetsMake(0, 0, self.wordNumLabel.frame.size.height, 0);
        
    }else{
        self.wordNumLabel.frame = CGRectMake(self.frame.size.width - self.wordNumLabel.frame.size.width-5, self.frame.size.height + self.contentInset.bottom-self.wordNumLabel.frame.size.height-5, self.wordNumLabel.frame.size.width, self.wordNumLabel.frame.size.height);
        self.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//判斷是否輸入的是emoji表情
- (BOOL)stringContainsEmoji:(NSString *)string{
    NSUInteger stringUtf8Length = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    if(stringUtf8Length >= 4 && (stringUtf8Length / string.length != 3)){
        return YES;
    }else{
        return NO;
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (self.allowEmoji) {
        return YES;
    }else {
    if ([self stringContainsEmoji:text]) {
        NSLog(@"輸入的是表情...");
        return NO;
    }else{
        NSLog(@"輸入的不是表情...");
        return YES;
    }
    }
}

代碼下載

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末澄耍,一起剝皮案震驚了整個(gè)濱河市顷级,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌听想,老刑警劉巖呜叫,帶你破解...
    沈念sama閱讀 217,734評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赞枕,死亡現(xiàn)場(chǎng)離奇詭異坛悉,居然都是意外死亡顺献,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門抑诸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)烂琴,“玉大人,你說(shuō)我怎么就攤上這事蜕乡。” “怎么了梗夸?”我有些...
    開封第一講書人閱讀 164,133評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵层玲,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我反症,道長(zhǎng)辛块,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,532評(píng)論 1 293
  • 正文 為了忘掉前任铅碍,我火速辦了婚禮润绵,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘胞谈。我一直安慰自己尘盼,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評(píng)論 6 392
  • 文/花漫 我一把揭開白布烦绳。 她就那樣靜靜地躺著卿捎,像睡著了一般。 火紅的嫁衣襯著肌膚如雪径密。 梳的紋絲不亂的頭發(fā)上午阵,一...
    開封第一講書人閱讀 51,462評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音享扔,去河邊找鬼底桂。 笑死,一個(gè)胖子當(dāng)著我的面吹牛惧眠,可吹牛的內(nèi)容都是我干的籽懦。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼锉试,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼猫十!你這毒婦竟也來(lái)了览濒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,153評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤拖云,失蹤者是張志新(化名)和其女友劉穎贷笛,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體宙项,經(jīng)...
    沈念sama閱讀 45,587評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡乏苦,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了尤筐。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片汇荐。...
    茶點(diǎn)故事閱讀 39,919評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖盆繁,靈堂內(nèi)的尸體忽然破棺而出掀淘,到底是詐尸還是另有隱情,我是刑警寧澤油昂,帶...
    沈念sama閱讀 35,635評(píng)論 5 345
  • 正文 年R本政府宣布革娄,位于F島的核電站,受9級(jí)特大地震影響冕碟,放射性物質(zhì)發(fā)生泄漏拦惋。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評(píng)論 3 329
  • 文/蒙蒙 一安寺、第九天 我趴在偏房一處隱蔽的房頂上張望厕妖。 院中可真熱鬧,春花似錦挑庶、人聲如沸言秸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)井仰。三九已至,卻和暖如春破加,著一層夾襖步出監(jiān)牢的瞬間俱恶,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工范舀, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留合是,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,048評(píng)論 3 370
  • 正文 我出身青樓锭环,卻偏偏與公主長(zhǎng)得像聪全,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子辅辩,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容