藤原とうふ店(自家用)

iOS开发:UITextField PlaceHolder垂直居

2018-02-26  本文已影响1193人  Abnerzj

一、需求

近期需要实现类似微信提现界面的功能,在输入提现金额用到UITextField控件来实现,需求是:
1,在没有输入金额时,默认展示字体较小的占位字符,有输入金额时,显示正常大小的金额,且占位字符要垂直居中显示。
2,用户把所有字符删除完时,要回到展示字体较小的占位字符,且占位字符要垂直居中显示。
3,用户点右侧的清除按钮清空所有内容时,要回到展示字体较小的占位字符,且占位字符要垂直居中显示。

下面是最终效果:


最终效果.gif

二、实现

1,要自定义占位字符串,就得用到UITextFieldattributedPlaceholder属性:

@property(nullable, nonatomic, copy)   NSAttributedString  *attributedPlaceholder NS_AVAILABLE_IOS(6_0); // default is nil

这里可以自定义文字字符的字体样式、文字颜色、文字段落样式等,可以参考NSAttributedString.h文件中的文字字符属性参数定义。这里主要说一下垂直居中,要实现垂直居中就得使用到段落样式属性NSParagraphStyleAttributeName

NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];

// 通过最小的行高来控制文字字符垂直居中,注意,文字字符垂直方向默认是底部对齐,所以你不能让它直接等于youTextFeild的行高,通过这种简单计算可以控制文字字符垂直居中显示。
style.minimumLineHeight = self.youTextFeild.font.lineHeight - (self.youTextFeild.font.lineHeight - [UIFont systemFontOfSize:16].lineHeight) * 0.5; 

NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"请输入提现金额" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16], NSParagraphStyleAttributeName : style}];

2,如果不处理第二点和第三点需求,那输入框内容为空时,占位文字的字体大小会跟UITextField的文本内容大小一样,同时位置也会向上偏移,如下:

占位文字变大.gif

我们可以通过设置UITextField的代理来处理,下面是完整代码:

#pragma mark UITextField Delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (range.length == 1 && range.location == 0 && [string isEqualToString:@""]) {
        self.youTextFeild.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"" attributes:nil]; // 避免占位字符由大变小跳动
        [self.youTextFeild performSelector:@selector(setAttributedPlaceholder:) withObject:[self getTextFeildAttributedPlaceholder] afterDelay:0.1f];
    }
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (self.isGetCashInterface && [textField isEqual:self.getCashTextFeild]) {
        self.youTextFeild.attributedPlaceholder = [self getTextFeildAttributedPlaceholder];
    }
    return YES;
}

- (NSAttributedString *)getTextFeildAttributedPlaceholder
{
    self.youTextFeild.font = [UIFont systemFontOfSize:50];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.minimumLineHeight = self.youTextFeild.font.lineHeight - (self.youTextFeild.font.lineHeight - [UIFont systemFontOfSize:16].lineHeight) * 0.5; // 垂直居中
    return [[NSAttributedString alloc] initWithString:@"请输入提现金额" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16], NSParagraphStyleAttributeName : style}];
}
上一篇 下一篇

猜你喜欢

热点阅读