UITextField的placeholder自定义

系统的 UITextFieldplaceholder,一般只有默认的样式,但是 UI 设计的时候往往会出现占位文字颜色,位置的等等不同的需求,那么就要修改 placeholder 的样式了。

placeholder字体和颜色

使用 NSMutableParagraphStyle 自定义样式

根据字体计算文字高度,使占位文字垂直居中

searchField.font = [UIFont systemFontOfSize:16.0];

NSMutableParagraphStyle *style = [searchField.font.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
// 通过字体计算文字的高度,保证文字显示出来的时候是垂直居中
style.minimumLineHeight = searchField.font.lineHeight - (searchField.font.font.lineHeight - [UIFont systemFontOfSize:12.0].lineHeight) / 2.0;
searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"输入您想要搜索的内容"
                                                                     attributes:@{
                                                                                  NSForegroundColorAttributeName: [UIColor whiteColor],
                                                                                  NSFontAttributeName : [UIFont systemFontOfSize:14.0],
                                                                                  NSParagraphStyleAttributeName : style
                                                                                  }
                                      
                                      ];
复制代码

左右垂直居中

重写UITextFielddrawPlaceholderInRect:(CGRect)rect的方法

- (void)drawPlaceholderInRect:(CGRect)rect {

	//  self.font.pointSize + 5 ,防止placeholderRect 的高度刚刚好等于文字的高度,显示出来后,文字底部有种被切掉一边的效果
	
    CGRect placeholderRect = CGRectMake(rect.origin.x+10, (rect.size.height- self.font.pointSize - 2)/2, rect.size.width, self.font.pointSize + 5);//设置距离
    
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineBreakMode = NSLineBreakByTruncatingTail;
    style.alignment = NSTextAlignmentCenter;
    NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:style,NSParagraphStyleAttributeName, self.font, NSFontAttributeName, [UIColor whiteColor], NSForegroundColorAttributeName, nil];
    
    [self.placeholder drawInRect:placeholderRect withAttributes:attr];
}
复制代码

转载于:https://juejin.im/post/5a93c944f265da4e721c9da4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值