您的当前位置:首页正文

UITextField-设置placeholder的正确姿势

来源:要发发知识网

1.需求说明

项目中经常会遇到各种各样的需求,比如输入框透明,边框以及内部的placeholder为白色,再或者placeholder要求居中。

样例截图

广大的iOS开发人员可能会想到各种方法,本人只举一些设置placeholder的颜色以及字体大小的常见用法。好,各位同行坐稳了,准备开车。

2 代码演示

2.1 iOS 6.0之前

//颜色设置
[self.textField setValue:color forKeyPath:@"_placeholderLabel.textColor"];
 //字体大小
[self.textField setValue:[UIFont boldSystemFontOfSize:fontSize] forKeyPath:@"_placeholderLabel.font"];

设置placeholder的居中方式的时候,通过该方法设置如下,会报错,知道的大神可以帮忙晚上一下.

 [textField setValue:[NSNumber numberWithInteger:NSTextAlignmentCenter] forKeyPath:@"_placeholderLabel.textAligment"];

2.2 iOS6之后 attributedPlaceholder属性

苹果官方文档原文对该属性的描述:

Discussion
This property is nil by default. If set, the placeholder string is drawn using a 70% gray color and the remaining style information (except the text color) of the attributed string. Assigning a new value to this property also replaces the value of the placeholder property with the same string data, albeit without any formatting information. Assigning a new value to this property does not affect any other style-related properties of the text field.

在设置placeholder的对齐方式的时候也使用了NSMutableParagraphStyle类。

Overview
The NSMutableParagraphStyle class adds methods to its superclass, NSParagraphStyle, for changing the values of the subattributes in a paragraph style attribute.See the NSParagraphStyle and NSAttributedString specifications for more information.

  _textField = [[UITextField alloc]initWithFrame:CGRectMake(24*HorizontalScale, 20*HorizontalScale+64, ScreenWidth - 48*HorizontalScale, 80*HorizontalScale)];
    
    _textField.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _textField.layer.borderWidth = 1;
    _textField.layer.cornerRadius = 4;
    
    //设置光标起始位置
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,10,_textField.height )];
    _textField.leftView = leftView;
    _textField.leftViewMode = UITextFieldViewModeAlways;

    CGRect frame = [@"输入楼盘名" boundingRectWithSize:CGSizeMake(MAXFLOAT, _textField.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
    //设置textFiled的段落格式
    NSMutableParagraphStyle *style = [_textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    //设置垂直对齐
    style.minimumLineHeight = _textField.font.lineHeight - (_textField.font.lineHeight - [UIFont systemFontOfSize:14.0].lineHeight) / 2.0;
    //水平对齐
    style.firstLineHeadIndent = (_textField.width - frame.size.width )*0.5 -DYNAMIC(20);
    //设置placeholder的样式
    _textField.attributedPlaceholder = [[NSAttributedString alloc]initWithString:@"输入楼盘名" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSParagraphStyleAttributeName:style,NSForegroundColorAttributeName:[UIColor blueColor]
}];
    
    [self.view addSubview:_textField];

未完待续....