iOS奇淫巧技iOS 开发~项目常用,经典内容收集O~1

一行代码实现UITextView的placeHolder

2017-06-08  本文已影响1019人  小小提莫酱
读书无用论的去死.jpg

前言

通过Category一行代码实现UITextView的placeHolder。搭配使用一行代码限制并统计UITextView输入字数效果更佳。

实现效果

ZWPlaceHolder+LimitCouner.gif

导入头文件

#import "UITextView+ZWPlaceHolder.h"
self.firstTextView.zw_placeHolder = @"向厂家反馈同业相关活动、产品信息、用于市场分析。";
    CGRect rect = CGRectMake(5, 230, [UIScreen mainScreen].bounds.size.width-10, 80);
    UITextView *textView = [[UITextView alloc] initWithFrame:rect];
    textView.layer.borderWidth = 1;
    textView.font = [UIFont systemFontOfSize:14];
    textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    textView.zw_placeHolder = @"向厂家反馈同业相关活动、产品信息、用于市场分析。";
    [self.view addSubview:textView];
textView.font = [UIFont systemFontOfSize:14];
textView.zw_placeHolderColor = [UIColor redColor];
调整placeHolder字体颜色.png

实现源码解析

#pragma mark - update
- (void)updatePlaceHolder{
    if (self.text.length) {
        [self.zw_placeHolderLabel removeFromSuperview];
        return;
    }
    self.zw_placeHolderLabel.font = self.font?self.font:self.cacutDefaultFont;
    self.zw_placeHolderLabel.textAlignment = self.textAlignment;
    self.zw_placeHolderLabel.text = self.zw_placeHolder;
    [self insertSubview:self.zw_placeHolderLabel atIndex:0];
}
#pragma mark - lazzing
-(UILabel *)zw_placeHolderLabel{
    UILabel *placeHolderLab = objc_getAssociatedObject(self, @selector(zw_placeHolderLabel));
    if (!placeHolderLab) {
        placeHolderLab = [[UILabel alloc] init];
        placeHolderLab.numberOfLines = 0;
        placeHolderLab.textColor = [UIColor lightGrayColor];
        objc_setAssociatedObject(self, @selector(zw_placeHolderLabel), placeHolderLab, OBJC_ASSOCIATION_RETAIN);
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePlaceHolder) name:UITextViewTextDidChangeNotification object:self];
    }
    return placeHolderLab;
}
// Default value: 5.0  The layout padding at the beginning and end of the line fragment rects insetting the layout width available for the contents.  This value is utilized by NSLayoutManager for determining the layout width.
@property(NS_NONATOMIC_IOSONLY) CGFloat lineFragmentPadding;
CGFloat x = lineFragmentPadding + textContainerInset.left + self.layer.borderWidth;

placeHolder的x坐标 = 光标偏移量+text偏移量+border边框宽度。
其他坐标同理算得。

如何使用

pod   'ZWPlaceHolder'
#import "UITextView+ZWPlaceHolder.h"

搭配使用

源码

cocoapod版本更新记录
上一篇下一篇

猜你喜欢

热点阅读