我已经对UITextField类进行了子类化,并编写了以下代码
- (void)drawPlaceholderInRect:(CGRect)rect
{
[self.placeHolderTextColor setFill];
[self.placeholder drawInRect:rect
withFont:self.placeHolderFont
lineBreakMode:NSLineBreakByTruncatingTail
alignment:NSTextAlignmentLeft];
}
我也写了一行代码:self.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
iOS6中,这个占位符文本居中对齐,但在iOS7中不是,它显示为顶部对齐。
虽然我输入的文本居中显示,但它只有占位符字符串出现问题。
我尝试了使用xib来设置占位符字符串,在XIB中它正常显示,但当我运行代码时,文本框的占位符就顶部对齐了。
有什么解决办法吗?
Vadoff的回答对我有用。以下是完整实现代码,可能会帮助到遇到同样问题的人。
drawInRect
方法在iOS7中已经弃用,drawInRectWithAttributes
可以使用。
- (void)drawPlaceholderInRect:(CGRect)rect
{
[self.placeHolderTextColor setFill];
CGRect placeholderRect = CGRectMake(rect.origin.x, (rect.size.height- self.placeHolderFont.pointSize)/2 - 2, rect.size.width, self.placeHolderFont.pointSize);
rect = placeholderRect;
if(iOS7) {
NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
style.lineBreakMode = NSLineBreakByTruncatingTail;
style.alignment = self.placeHolderTextAlignment;
NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:style,NSParagraphStyleAttributeName, self.placeHolderFont, NSFontAttributeName, self.placeHolderTextColor, NSForegroundColorAttributeName, nil];
[self.placeholder drawInRect:rect withAttributes:attr];
}
else {
[self.placeholder drawInRect:rect
withFont:self.placeHolderFont
lineBreakMode:NSLineBreakByTruncatingTail
alignment:self.placeHolderTextAlignment];
}
}