教大家如何给UITextView添加placeholder扩展

简介:

如何扩展UITextView以追加placeholder功能呢?

我们的需求是:追加placeholder功能

方案讨论:

  • 通过继承UITextView的方式
  • 通过扩展UITextView的方式

分析:方案1使用继承方式实现起来更简单,但是使用起来就没有那么方便;方案2 使用扩展的方式,实现起来稍比前者复杂,但是外部使用起来更简单

方案定位:采用扩展的方式,以极简的风格作为参考依据。

Tip:所谓极简,即对外接口最简,对内部可以很复杂

扩展头文件

#import <UIKit/UIKit.h>

/**
 * @author huangyibiao
 *
 * 给UITextView添加placeholder
 *
 * @note 注意,此扩展有点小问题,如果在添加placeholder后,又直接赋值Text属性,则不会自动消失
 *       解决办法是:如果有初始值,先给text,再设置holder
 */
@interface UITextView (HDFTextView)

/**
 * 占位提示语
 */
@property (nonatomic, copy)   NSString *hdf_placeholder;

/**
 * 占位提示语的字体颜色
 */
@property (nonatomic, strong) UIColor *hdf_placeholderColor;

/**
 * 占位提示语的字体
 */
@property (nonatomic, strong) UIFont  *hdf_placeholderFont;

/**
 * 占位提示语标签
 */
@property (nonatomic, strong, readonly) UILabel *hdf_placeholderLabel;


@end
##说明:头文件中其实只需要公开hdf_placeholderLabel属性就可以实现了,但是依然公开了对hdf_placeholderLabel直接属性,可以根据个人习惯使用。扩展是不能扩展属性的,但是这里写成了属性的形式,其实只是利用了getter/setter方式,重写其API。内部会使用动态运行时机制来完成扩展伪属性的功能(称为伪属性是因为本质上是扩展不了属性的)

实现文件

#import "UITextView+HDFTextView.h"

static const void *s_hdfTextViewPlaceholderLabelKey = "s_hdfTextViewPlaceholderLabelKey";
static const void *s_hdfTextViewPlaceholderTextKey = "s_hdfTextViewPlaceholderTextKey";

@interface UIApplication (HDFTextViewHolder)

@end

@implementation UIApplication (HDFTextViewHolder)

- (void)hdf_placehoderTextChange:(NSNotification *)nofitication {
  if (kIsIOS7OrLater) {
    return;
  }
  UITextView *textView = nofitication.object;
  if ([textView isKindOfClass:[UITextView class]]) {
    if (!kIsEmptyString(textView.text)) {
      textView.hdf_placeholderLabel.text = @"";
    } else {
      textView.hdf_placeholderLabel.text = textView.hdf_placeholder;
    }
  }
}

@end

@interface UITextView (HDFPlaceholderTextView)

@property (nonatomic, strong) UILabel *placeholderLabel;

@end

@implementation UITextView (HDFPlaceholderTextView)

- (void)setPlaceholderLabel:(UILabel *)placeholderLabel {
  objc_setAssociatedObject(self,
                           s_hdfTextViewPlaceholderLabelKey,
                           placeholderLabel,
                           OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UILabel *)placeholderLabel {
  UILabel *label = objc_getAssociatedObject(self, s_hdfTextViewPlaceholderLabelKey);

  if (label == nil || ![label isKindOfClass:[UILabel class]]) {
    label = [[UILabel alloc] init];
    label.textAlignment = NSTextAlignmentLeft;
    label.font = self.font;
    label.backgroundColor = [UIColor clearColor];
    label.textColor = kHolderTipColor;
    [self addSubview:label];

    kWeakObject(self);
    self.placeholderLabel = label;
    CGFloat left = kIsIOS7OrLater ? 5 : 7;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
      make.edges.mas_equalTo(weakObject).insets(UIEdgeInsetsMake(7.5, left, 0, 0));
    }];
    label.enabled = NO;

    [kNotificationCenter addObserver:kIsIOS7OrLater ? self : [UIApplication sharedApplication]
                            selector:@selector(hdf_placehoderTextChange:)
                                name:UITextViewTextDidChangeNotification
                              object:nil];
  }

  return label;
}

@end

@implementation UITextView (HDFTextView)

- (void)hdf_placehoderTextChange:(NSNotification *)notification {
  if (kIsIOS7OrLater) {
    if (!kIsEmptyString(self.text)) {
      self.placeholderLabel.text = @"";
    } else {
      self.placeholderLabel.text = self.hdf_placeholder;
    }
  }
}

- (UILabel *)hdf_placeholderLabel {
  return self.placeholderLabel;
}

- (void)setHdf_placeholder:(NSString *)hdf_placeholder {
  if (kIsEmptyString(hdf_placeholder)) {
    objc_setAssociatedObject(self, s_hdfTextViewPlaceholderLabelKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self.placeholderLabel removeFromSuperview];
    return;
  }

  objc_setAssociatedObject(self,
                           s_hdfTextViewPlaceholderTextKey,
                           hdf_placeholder,
                           OBJC_ASSOCIATION_COPY_NONATOMIC);

  if (!kIsEmptyString(self.text)) {
    self.placeholderLabel.text = @"";
  } else {
    self.placeholderLabel.text = hdf_placeholder;
  }
}

- (NSString *)hdf_placeholder {
  return objc_getAssociatedObject(self, s_hdfTextViewPlaceholderTextKey);
}

- (void)setHdf_placeholderColor:(UIColor *)hdf_placeholderColor {
  self.placeholderLabel.textColor = hdf_placeholderColor;
}

- (UIColor *)hdf_placeholderColor {
  return self.placeholderLabel.textColor;
}

- (void)setHdf_placeholderFont:(UIFont *)hdf_placeholderFont {
  self.placeholderLabel.font = hdf_placeholderFont;
}

- (UIFont *)hdf_placeholderFont {
  return self.placeholderLabel.font;
}

@end
说明:这里的实现文件中使用了运行时机制(runtime)来实现,这里对文本改变的监听,交给了自己和UIApplication,是为了兼容到IOS6.0,在6.0下,交给自己是不可行的,会崩溃,因此移交给UIApplication单例对象来管理。

############提示:这里使用了Masonary这个自动布局的三方库,让这个placeholderlabel自动根据uitextview的大小变化而变化。代码中使用了判断IOS系统,判断是否为空串的代码,这里不写出来了,自己替掉即可。

下面就是使用了,使用起来就很简单了

  self.remarkView.text = @"哈哈,很简单吧";
  self.remarkView.hdf_placeholder = @"写点什么...";

备注:当需求中需要给textview添加placeholder时,网上的都是继承的方式,还需要修改很多地方,这是不可行的,所以我才提出这个问题来,然后做出了自己的解决方案。如果对大家有用,请放心地拿去用吧。

兼容IOS6.0及其以上版本
目录
相关文章
|
安全 编译器 C语言
C语言安全编程:避免缓冲区溢出等安全。
C语言安全编程:避免缓冲区溢出等安全。
|
10月前
|
Java 关系型数据库 数据库连接
使用 Spring Boot 执行数据库操作:全面指南
使用 Spring Boot 执行数据库操作:全面指南
1223 1
|
机器学习/深度学习 人工智能 安全
构建未来:AI驱动的自适应网络安全防御系统云端守卫:云计算环境下的网络安全与信息保护策略
【5月更文挑战第27天】 在数字化时代,网络安全威胁持续进化,传统的安全措施逐渐显得力不从心。本文探讨了人工智能(AI)技术如何革新现代网络安全防御系统,提出一个基于AI的自适应网络安全模型。该模型结合实时数据分析、模式识别和自我学习机制,能够动态调整防御策略以应对未知攻击。文章不仅分析了此模型的核心组件,还讨论了实施过程中的挑战与潜在效益。通过引入AI,我们展望一个更加智能且具有弹性的网络安全环境,旨在为未来的网络防护提供一种创新思路。
|
弹性计算 容灾 定位技术
阿里云服务器地域和可用区常见问题及官方资料解答
阿里云服务器同一地域分为多个可用区,不同地域的实例之间内网互不相通;选择靠近您客户的地域,可降低网络时延、提高您客户的访问速度。本文介绍阿里云地域和可用区的概念、选择指导、两者的关系以及阿里云支持的地域和可用区列表。
1810 0
阿里云服务器地域和可用区常见问题及官方资料解答
|
搜索推荐 自然语言处理 算法
|
存储 缓存 NoSQL
微服务架构四大金刚利器
概述 互联网应用发展到今天,从单体应用架构到SOA以及今天的微服务,随着微服务化的不断升级进化,服务和服务之间的稳定性变得越来越重要,分布式系统之所以复杂,主要原因是分布式系统需要考虑到网络的延时和不可靠,微服务很重要的一个特质就是需要保证服务幂等,保证幂等性很重要的前提需要分布式锁控制并发,同时缓存、降级和限流是保护微服务系统运行稳定性的三大利器。
11070 0
|
分布式计算 算法 大数据
支撑EB级规模的大数据平台深度揭秘
陈鹏宇于2010年加入阿里巴巴,在阿里启动大数据战略早期即参与整个大数据业务发展的过程。作为数据平台见证者和建设者,他以独特的视角,对大数据平台的技术演进历程等做了分享,并从用户角度对数加平台上层工具、服务所适用的场景进行了深入阐述。
11183 0
|
流计算 Java Scala
带你读《Flink原理、实战与性能优化》之二:环境准备
这是一部以实战为导向,能指导读者零基础掌握Flink并快速完成进阶的著作,从功能、原理、实战和调优等4个维度循序渐进地讲解了如何利用Flink进行分布式流式应用开发。作者是该领域的资深专家,现就职于第四范式,曾就职于明略数据。
|
jenkins 应用服务中间件 持续交付
Jenkins +Gradle实现Android自动化构建(学习笔记三十二)
https://blog.csdn.net/mabeijianxi/article/details/52680283 http://www.liuling123.com/2016/10/jenkins-gradle-auto-build.html Jenkins简介 Jenkins是一个开源软件项目,旨在提供一个开放易用的软件平台,使软件的持续集成变成可能。
2811 0