iOS学习之----------自定义UITextView

本文介绍了如何在iOS中自定义一个带placeholder的UITextView,通过结合UILabel实现类似UITextField的placeholder效果。步骤包括创建自定义类,添加UILabel,设置布局,定义外部属性,监听文本变化以控制placeholder的显示和隐藏,以及重写setFont方法保持字体同步。

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

1、自定义UITextView(将UITextView和UILabel想结合使用)

使用UITextView的时候需要在text显示一段提示文字,但是UITextView没有像UITextField一样的 placehoder属性对其进行设置,因此需要将将UITextView和UILabel相结合使用,自定义一个UITextView。

1、创建textView类继承于UITextView

2、在initWithFrame:(CGRect)frame中添加UILabel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        // Initialization code
        UILabel *placehoderLabel = [[UILabel alloc]init];
        [self addSubview:placehoderLabel];
        self.placehoderLabel = placehoderLabel;

        //设置textView(self)的背景色为clearColor

        self.backgroundColor = [UIColor clearColor];

        //设置label的背景色为clearColor

        placehoderLabel.backgroundColor = [UIColor clearColor];
        placehoderLabel.numberOfLines = 0;

    }
    return self;
}

3、设置label的frame

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.placehoderLabel.x = 5;
    self.placehoderLabel.y = 7;
     self.placehoderLabel.width = self.width - self.placehoderLabel.x;
    CGSize maxSize = CGSizeMake(self.placehoderLabel.width, MAXFLOAT);
    CGSize placehoderSize = [self.placehoder sizeWithFont:self.placehoderLabel.font constrainedToSize:maxSize];
    self.placehoderLabel.height = placehoderSize.height;
}

4、定义外部属性,其他人可以对textView的placehoder和placehoderColor进行修改

@property (nonatomic,copy)NSString *placehoder;
@property (nonatomic,strong)UIColor *placehoderColor;


5、重写两个属性的set方法提供给外部的方法可以对这些属性对其进行设置

-(void)setPlacehoderColor:(UIColor *)placehoderColor
{
    _placehoderColor = placehoderColor;
    self.placehoderLabel.textColor = _placehoderColor;
}

- (void)setPlacehoder:(NSString *)placehoder
{
#warning 如果是copy  set最好这样写
    _placehoder = [placehoder copy];
    self.placehoderLabel.text = placehoder;
    //重新刷新frame (当在中途换了文字需要重新计算frame)
    [self setNeedsLayout];
}


6、设置监听,监听textView的文本信息改变的监听

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        //当self的文字发生改变  self就会自动发出一个UITextViewTextDidChangeNotification通知
        [center addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];

7、设置label的显示与隐藏

当有文本信息输入的时候,将label隐藏

- (void)textDidChange
{
    self.placehoderLabel.hidden = (self.text.length != 0);
}

8、重写setFont方法防止其他人在使用的时候 修改字体大小

- (void)setFont:(UIFont *)font
{
    [super setFont:font];
    self.placehoderLabel.font = font;
    //重新刷新frame (当在中途换了文字需要重新计算frame)
    [self setNeedsLayout];
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值