您的位置:首页 > 移动开发 > IOS开发

iOS 自定义textField 显示下划线 左边显示文字 自定义placeholder的颜色和字体

2016-06-01 11:29 441 查看
本篇文章是记录下自己学习的内容 , 代码比较low,请各位大神多多指教

效果为


主要实现方法:

实现下划线。重写drawRect方法:

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    [[UIColor redColor] set];//设置下划线颜色 这里是红色 可以自定义

    
    CGFloat y = CGRectGetHeight(self.frame);
    CGContextMoveToPoint(context, 0, y);
    CGContextAddLineToPoint(context, CGRectGetWidth(self.frame), y);
    //设置线的宽度
    CGContextSetLineWidth(context, 2);
    //渲染
显示到self上
    CGContextStrokePath(context);
}

接下来自定义textField的leftView, 这里因为要显示文字,所以用一个label来实现, 也可以使用自定义的view
。在初始化的时候设置label为leftView, 并设置leftView的mode

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        UILabel *label = [[UILabel alloc] init];
        self.leftView = label;
        self.leftViewMode = UITextFieldViewModeAlways;
        _leftLabel = label;
    }
    return self;
}
_leftLabel是自己定义的一个全局变量, 这里可以看到leftLabel并没有frame
接下来重写textField的

- (CGRect)leftViewRectForBounds:(CGRect)bounds方法, 给leftView设置frame

- (CGRect)leftViewRectForBounds:(CGRect)bounds
{

    
    [super leftViewRectForBounds:bounds];
    CGRect frame = bounds;

    //这里设置为leftView的宽是textField的0.3倍,
    frame.size.width = bounds.size.width * 0.3;

    
    return frame;
}
然后在.h文件里面生成属性, 方便外界修改;

//左侧显示的文字
@property (nonatomic , copy) NSString *leftTitle;
//左侧文字的颜色
@property (nonatomic , strong) UIColor *leftTitleColor;
/**只有在设置了placeholder之后才会有效**/
@property (nonatomic , strong) UIColor *placeholderColor;

@property (nonatomic , strong) UIFont *placeholderFont;Font;
接下来重写属性的set方法

- (void)setPlaceholderColor:(UIColor *)placeholderColor
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSForegroundColorAttributeName] = placeholderColor;
    NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:self.placeholder attributes:dict];
    [self setAttributedPlaceholder:attribute];
}
- (void)setPlaceholderFont:(UIFont *)placeholderFont
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSFontAttributeName] = placeholderFont;
    NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:self.placeholder attributes:dict];
    [self setAttributedPlaceholder:attribute];
}
- (void)setLeftTitleColor:(UIColor *)leftTitleColor
{
    _leftTitleColor = leftTitleColor;
    [_leftLabel setTextColor:leftTitleColor];
}
- (void)setLeftTitle:(NSString *)leftTitle
{
    _leftTitle = leftTitle;
    [_leftLabel setText:leftTitle];
}
说明:之所以要在设置placeholder之后再设置placeholderColor和placeholderFont是因为我是用的是    [self setAttributedPlaceholder:attribute];来设置的,
这里是通过初始化self。placeholder来实现, 如果先设置placeholderColor,因为此时placeholder为空, 会设置失败, placeholderFont同上,

到这里就全部设置完毕了。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 字体 textField