iOS UITextView问题一网打尽(占位文字、汉字输入字数计算、自动高度改变)

本文探讨了在iOS开发中使用UITextView时遇到的问题,包括如何设置占位文字placeHolder,如何在输入汉字时实时统计字数,以及在tableViewCell中实现textView高度自适应。通过自定义category添加placeHolder属性,监听textView的改变以统计字数,并在textViewDidChange代理方法中处理中文输入的特殊情况。同时,通过调整tableView的scrollEnabled属性和约束设置,使cell随textView内容动态调整高度。

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

在iOS开发中,UITextView是一个使用还算比较多的控件。但是用过的人都知道,UITextView有很多存在的问题,今天就来一一说它一说。

一、设置textView的placeHolder

首先需要解决的就是占位文字placeHolder的问题,与UITextField相比,UITextView并没有相应的placeholder属性设置占位文字,但是可以通过category的方式给textView添加placeHolder属性,这样就可以在任何需要的使用直接使用了,我写好了一个category UITextView+PlaceHolder,大概如下:
.h中

#import <UIKit/UIKit.h>

@interface UITextView (PlaceHolder)

@property (nonatomic, copy) NSString *placeHolder;

@end

.m中:

#import "UITextView+PlaceHolder.h"
#import <objc/runtime.h>

#define kScreenW [UIScreen mainScreen].bounds.size.width
static const void *textView_key = @"placeHolder";

@interface UITextView ()
@end

@implementation UITextView (PlaceHolder)

- (void)setPlaceHolder:(NSString *)placeHolder
{
    if (placeHolder != self.placeHolder) {
        objc_setAssociatedObject(self, textView_key, placeHolder, OBJC_ASSOCIATION_COPY_NONATOMIC);
        
        UILabel *placeHolderLb = [[UILabel alloc] initWithFrame:CGRectMake(2, 7, kScreenW-2*16, 21)];
        placeHolderLb.tag = 1000;
        placeHolderLb.contentMode = UIViewContentModeTop;
        placeHolderLb.numberOfLines = 0;
        placeHolderLb.textColor = [UIColor redColor];
        placeHolderLb.font = [UIFont systemFontOfSize:16];
        placeHolderLb.alph
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值