ios自定义UITextView 支持placeholder的方法

本文介绍了一个自定义的UITextView组件,该组件支持设置占位符并可根据文本输入情况自动显示或隐藏占位符。通过监听UITextViewTextDidChangeNotification通知来实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果图:212830_owy9_1186234.gif


h文件

@interface YLTextView : UITextView
@property (copy ,nonatomic)NSString *placeHoder;
@property (assign,nonatomic)BOOL hidePlaceHoder; //是否对placeHoder进行隐藏
@end


m 文件

//
//  YLTextView.m
//  YangLand
//
//  Created by 赵大财 on 16/3/13.
//  Copyright © 2016年 tshiny. All rights reserved.
//

#import "YLTextView.h"

@interface YLTextView ()

@property (weak ,nonatomic)UILabel *placeHoderLabel;

@end

@implementation YLTextView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.font = [UIFont systemFontOfSize:13];
    }
    return self;
}

-(void)setFont:(UIFont *)font {
    [super setFont:font];
    self.placeHoderLabel.font = font;
    [self.placeHoderLabel sizeToFit]; //文字的大小 就是label的尺寸
}

-(void)setPlaceHoder:(NSString *)placeHoder {
    _placeHoder = placeHoder;
    self.placeHoderLabel.text = placeHoder;
    [self.placeHoderLabel sizeToFit];
}

- (void)setHidePlaceHoder:(BOOL)hidePlaceHoder {
    _hidePlaceHoder = hidePlaceHoder;
    self.placeHoderLabel.hidden = hidePlaceHoder;
}

- (UILabel *)placeHoderLabel {
    if (!_placeHoderLabel) {
        UILabel *placeHoderLabel = [[UILabel alloc]init];
        [self addSubview:placeHoderLabel];
        _placeHoderLabel = placeHoderLabel;
    }
    return _placeHoderLabel;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.placeHoderLabel.x = 10;
    self.placeHoderLabel.y = 10;
}

@end


控制器的使用

  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextViewTextDidChangeNotification object:nil]; //监听文字改变
  
//文字改变方法   
- (void)textChange {
    if (self.textView.text.length) {
        _textView.hidePlaceHoder = YES;
    }else {
        _textView.hidePlaceHoder = NO;
    }
}


- (YLTextView *)textView {
    if (!_textView) {
        _textView = [[YLTextView alloc]initWithFrame:self.view.bounds];
        _textView.delegate = self;
        _textView.alwaysBounceVertical = YES; //这是让textView可上下滑动
        _textView.placeHoder = @"请发表今天的心情...";
        _textView.font = [UIFont systemFontOfSize:20];
    }
    return _textView;
}


转载于:https://my.oschina.net/zhaodacai/blog/647547

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值