IOS将文本占位符对齐到中心和左对齐

时间:2016-11-10 09:57:44

标签: ios objective-c uitextfield placeholder

我正在创建一个提交反馈的IOS表单。

我希望占位符文本垂直居中,并在文本字段中左对齐水平

我试过这个

- (void)drawPlaceholderInRect:(CGRect)rect {
    [RGB(36, 84, 157) setFill];

    UIFont *font = [UIFont SingPostLightItalicFontOfSize:_placeholderFontSize fontKey:kSingPostFontOpenSans];
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    NSDictionary *attributes = @{ NSFontAttributeName: font,
                                  NSParagraphStyleAttributeName: paragraphStyle,
                                  NSForegroundColorAttributeName: [UIColor blackColor]};
    [[self placeholder] drawInRect:rect withAttributes:attributes];

}

但占位符文字位于顶部垂直方向。我们怎样才能实现黄金。非常感谢

enter image description here

2 个答案:

答案 0 :(得分:1)

以下代码将解决您的问题。我亲自尝试过。这只是代码的另一行。

- (void)drawPlaceholderInRect:(CGRect)rect {

       CGFloat fontSize = 18;
       UIFont *font = [UIFont systemFontOfSize:fontSize];
       NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
       paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
       paragraphStyle.alignment = NSTextAlignmentLeft;

       NSDictionary *attributes = @{ NSFontAttributeName: font,
                              NSParagraphStyleAttributeName: paragraphStyle,
       NSForegroundColorAttributeName: [UIColor blackColor]};

       CGRect newRect = CGRectInset(rect, 0, rect.size.height/2 - fontSize/2);
       [[super placeholder] drawInRect:newRect withAttributes:attributes];
}

答案 1 :(得分:0)

你可以把占位符的“y”位置意味着你的“rect”值作为文本字段高度/ 2.如果你使用textfield的默认属性作为水平对齐的占位符,可以使用更多解决方案。

喜欢:

var tt : UITextField
        tt.placeholder = ""