我有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中它显示正确,但是当我运行代码时,文本字段占位符是顶部对齐的。
任何解决方法?
瓦多夫的答案对我有用。这仍然是完整的实施方案,可能会帮助遇到相同问题的任何人。
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];
}
}
在iOS7中,drawInRect方法的行为似乎有所不同,您可以尝试添加以下行并将其用作绘制的矩形。它也向下兼容iOS7之前的版本。
CGRect placeholderRect = CGRectMake(rect.origin.x, (rect.size.height- self.font.pointSize)/2, rect.size.width, self.font.pointSize);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句