ZKPlaceholderTextView

//
//  ZKPlaceholderTextView.h
//  WaterProofer
//
//  Created by HELLO WORLD on 2019/9/18.
//  Copyright © 2019年 WaterProofer. All rights reserved.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface ZKPlaceholderTextView : UITextView

@property(copy,nonatomic)   NSString *placeholder;

@property(strong,nonatomic) NSIndexPath * indexPath;

//最大长度设置
@property(assign,nonatomic) NSInteger maxTextLength;

//更新高度的时候
@property(assign,nonatomic) float updateHeight;


/*
 增加text 长度限制
  @param maxLength
  @param limit
 */
-(void)addMaxTextLengthWithMaxLength:(NSInteger)maxLength andEvent:(void(^)(ZKPlaceholderTextView*text))limit;
/**
 *  开始编辑 的 回调
 *
 *  param begin
 */
-(void)addTextViewBeginEvent:(void(^)(ZKPlaceholderTextView*text))begin;

/**
 *  结束编辑 的 回调
 *
 *  param begin
 */
-(void)addTextViewEndEvent:(void(^)(ZKPlaceholderTextView*text))End;

-(void)setPlaceholderColor:(UIColor*)color;

-(void)setPlaceholderFont:(UIFont*)font;
// 设置透明度
-(void)setPlaceholderOpacity:(float)opacity;
@end

NS_ASSUME_NONNULL_END
ZKPlaceholderTextView.h
//
//  ZKPlaceholderTextView.m
//  WaterProofer
//
//  Created by HELLO WORLD on 2019/9/18.
//  Copyright © 2019年 WaterProofer. All rights reserved.
//

#import "ZKPlaceholderTextView.h"
#define kTopY 7.0
#define kLeftX 5.0

@interface ZKPlaceholderTextView()<UITextViewDelegate>
@property(strong,nonatomic) UIColor *placeholder_color;
@property(strong,nonatomic) UIFont * placeholder_font;
/**
 *   显示 Placeholder
 */
@property(strong,nonatomic,readonly)  UILabel *PlaceholderLabel;

@property(assign,nonatomic) float placeholdeWidth;

@property(copy,nonatomic) id eventBlock;
@property(copy,nonatomic) id BeginBlock;
@property(copy,nonatomic) id EndBlock;
@end

@implementation ZKPlaceholderTextView

#pragma mark - life cycle

- (id) initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        [self awakeFromNib];
    }
    return self;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DidChange:) name:UITextViewTextDidChangeNotification object:self];
    
    //UITextViewTextDidBeginEditingNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewBeginNoti:) name:UITextViewTextDidBeginEditingNotification object:self];
    
    //UITextViewTextDidEndEditingNotification
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewEndNoti:) name:UITextViewTextDidEndEditingNotification object:self];
    
    float left=kLeftX,top=kTopY,hegiht=30;
    
    self.placeholdeWidth=CGRectGetWidth(self.frame)-2*left;
    
    _PlaceholderLabel=[[UILabel alloc] initWithFrame:CGRectMake(left, top
                                                                , _placeholdeWidth, hegiht)];
    
    _PlaceholderLabel.numberOfLines=0;
    _PlaceholderLabel.lineBreakMode=NSLineBreakByCharWrapping|NSLineBreakByWordWrapping;
    [self addSubview:_PlaceholderLabel];
    
    
    [self defaultConfig];
    
}
-(void)layoutSubviews
{
    float left=kLeftX,top=kTopY,hegiht=self.bounds.size.height;
    self.placeholdeWidth=CGRectGetWidth(self.frame)-2*left;
    CGRect frame=_PlaceholderLabel.frame;
    frame.origin.x=left;
    frame.origin.y=top;
    frame.size.height=hegiht;
    frame.size.width=self.placeholdeWidth;
    _PlaceholderLabel.frame=frame;
    
    [_PlaceholderLabel sizeToFit];
    
}

-(void)dealloc{
    
    [_PlaceholderLabel removeFromSuperview];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
#pragma mark - System Delegate
#pragma mark - custom Delegate
#pragma mark - Event response

-(void)defaultConfig
{
    self.placeholder_color = [UIColor lightGrayColor];
    self.placeholder_font  = [UIFont systemFontOfSize:14];
    self.maxTextLength=1000;
    self.layoutManager.allowsNonContiguousLayout=NO;
    
    
}

-(void)addMaxTextLengthWithMaxLength:(NSInteger)maxLength andEvent:(void (^)(ZKPlaceholderTextView *text))limit
{
    if (maxLength>0) {
        
        _maxTextLength=maxLength;
        
    }
    
    if (limit) {
        _eventBlock=limit;
        
    }
}

-(void)addTextViewBeginEvent:(void (^)(ZKPlaceholderTextView *))begin{
    
    _BeginBlock=begin;
}

-(void)addTextViewEndEvent:(void (^)(ZKPlaceholderTextView *))End{
    _EndBlock=End;
}

-(void)setUpdateHeight:(float)updateHeight{
    
    CGRect frame=self.frame;
    frame.size.height=updateHeight;
    self.frame=frame;
    _updateHeight=updateHeight;
}

//供外部使用的 api

-(void)setPlaceholderFont:(UIFont *)font
{
    self.placeholder_font=font;
}
-(void)setPlaceholderColor:(UIColor *)color
{
    self.placeholder_color=color;
    
}
-(void)setPlaceholderOpacity:(float)opacity
{
    if (opacity<0) {
        opacity=1;
    }
    self.PlaceholderLabel.layer.opacity=opacity;
}


#pragma mark - Noti Event

-(void)textViewBeginNoti:(NSNotification*)noti{
    
    if (_BeginBlock) {
        void(^begin)(ZKPlaceholderTextView*text)=_BeginBlock;
        begin(self);
    }
}
-(void)textViewEndNoti:(NSNotification*)noti{
    
    if (_EndBlock) {
        void(^end)(ZKPlaceholderTextView*text)=_EndBlock;
        end(self);
    }
}

-(void)DidChange:(NSNotification*)noti{
    
    if (self.placeholder.length == 0 || [self.placeholder isEqualToString:@""]) {
        _PlaceholderLabel.hidden=YES;
    }
    
    if (self.text.length > 0) {
        _PlaceholderLabel.hidden=YES;
    }
    else{
        _PlaceholderLabel.hidden=NO;
    }
    
    NSString *lang = [[self.nextResponder textInputMode] primaryLanguage]; // 键盘输入模式
    
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入,包括简体拼音,健体五笔,简体手写
        UITextRange *selectedRange = [self markedTextRange];
        //获取高亮部分
        UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
        if (!position) {
            if (self.text.length > self.maxTextLength) {
                self.text = [self.text substringToIndex:self.maxTextLength];
            }
        }
        // 有高亮选择的字符串,则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
    else{
        if (self.text.length > self.maxTextLength) {
            self.text = [ self.text substringToIndex:self.maxTextLength];
        }
    }
    
    
    if (_eventBlock && self.text.length > self.maxTextLength) {
        
        void (^limint)(ZKPlaceholderTextView*text) =_eventBlock;
        
        limint(self);
    }
    
}

#pragma mark - private method

+(float)boundingRectWithSize:(CGSize)size withLabel:(NSString *)label withFont:(UIFont *)font{
    NSDictionary *attribute = @{NSFontAttributeName:font};
    
    // CGSize retSize;
    CGSize retSize = [label boundingRectWithSize:size
                                         options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                      attributes:attribute
                                         context:nil].size;
    
    return retSize.height;
    
}

#pragma mark - getters and Setters

-(void)setText:(NSString *)tex{
    if (tex.length>0) {
        _PlaceholderLabel.hidden=YES;
    }
    [super setText:tex];
}

-(void)setPlaceholder:(NSString *)placeholder{
    if (placeholder.length == 0 || [placeholder isEqualToString:@""]) {
        _PlaceholderLabel.hidden=YES;
    }
    else
    {
        _PlaceholderLabel.text=placeholder;
        _placeholder=placeholder;
        
        //        float  height=  [ZKPlaceholderTextView boundingRectWithSize:CGSizeMake(_placeholdeWidth, MAXFLOAT) withLabel:_placeholder withFont:_PlaceholderLabel.font];
        //        if (height>CGRectGetHeight(_PlaceholderLabel.frame) && height< CGRectGetHeight(self.frame)) {
        //
        //            CGRect frame=_PlaceholderLabel.frame;
        //            frame.size.height=height;
        //            _PlaceholderLabel.frame=frame;
        //
        //        }
    }
    
}
-(void)setPlaceholder_font:(UIFont *)placeholder_font
{
    _placeholder_font=placeholder_font;
    _PlaceholderLabel.font=placeholder_font;
}

-(void)setPlaceholder_color:(UIColor *)placeholder_color
{
    _placeholder_color=placeholder_color;
    _PlaceholderLabel.textColor=placeholder_color;
}

@end
ZKPlaceholderTextView.m
- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    //文本输入框
    _noteTextView = [[ZKPlaceholderTextView alloc]init];
    _noteTextView.keyboardType = UIKeyboardTypeDefault;
    //文字样式
    _noteTextView.maxTextLength = 200;
    [_noteTextView setTextColor:ColorHex_999999];
    _noteTextView.delegate = self;
    _noteTextView.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    _noteTextView.placeholder= @"请输入备注信息";
    [_noteTextView setPlaceholderFont:[UIFont fontWithName:@"PingFangSC-Regular" size:14]];
    self.noteTextView.returnKeyType = UIReturnKeyDone;
    [self.noteTextView setPlaceholderColor:[UIColor lightGrayColor]];
    [self.noteTextView setPlaceholderOpacity:1];
    _noteTextView.textContainerInset = UIEdgeInsetsMake(7, 0, 0, 0);
    [_baseView addSubview:_noteTextView];
    [_noteTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(_baseView);
    }];
    
    _fontNums = [[UILabel alloc] init];
    _fontNums.text = @"0/200";
    _fontNums.textColor = ColorHex_666666;
    _fontNums.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    [_baseView addSubview:_fontNums];
    [_fontNums mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.offset(0);
    }];
}
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    //当前输入字数
    if (_noteTextView.text.length > 140){
        //[self showManagerErrorTitle:@"输入内容已超过140字"];
        return NO;
    }
    
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
    }
    _fontNums.text = [NSString stringWithFormat:@"%ld/200",(unsigned long)text.length];

    return YES;
}
View Code

 

转载于:https://www.cnblogs.com/kingstudy/p/11544278.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值