代码之家  ›  专栏  ›  技术社区  ›  lostInTransit

以编程方式创建的UITextField的占位符文本未居中

  •  44
  • lostInTransit  · 技术社区  · 14 年前

    我正在以编程方式创建UITextField并将其放置在UIView中。字体大小设置为15.0f(系统字体)。但是出现的占位符在文本视图中没有居中。有人知道怎么解决吗?

    我在SO上找到了一些模糊文本等的引用,并尝试将textfield的框架设置为整数值,但没有什么区别。

    UITextField *txtField = [[UITextField alloc] initWithFrame:CGRectMake(5.0f, 6.0f, 278.0f, 32.0f)];
    [txtField setPlaceholder:@"My placeholder"];
    [txtField setFont:[UIFont systemFontOfSize:15.0]];
    [txtField setBorderStyle:UITextBorderStyleRoundedRect];
    [txtField setAutocorrectionType:UITextAutocorrectionTypeNo];
    [txtField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [txtField setKeyboardType:UIKeyboardTypeEmailAddress];
    [txtField setReturnKeyType:UIReturnKeyDone];
    [txtField setClearButtonMode:UITextFieldViewModeWhileEditing];
    

    谢谢你的帮助

    注意:我的意思是文本不是垂直居中的文本字段(它有点向上)。因此,设置文本对齐不是解决方案。

    添加问题的图像以进行澄清-如图所示,占位符文本更倾向于顶部,而不是垂直于中心。 alt text

    4 回复  |  直到 7 年前
        1
  •  58
  •   DiscDev    12 年前

    您需要添加:

    txtField.textAlignment = NSTextAlignmentCenter; // Pre-iOS6 SDK: UITextAlignmentCenter
    

    如何垂直居中

    txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
        2
  •  18
  •   AndroC    11 年前

    这在iOS7上并不像预期的那样工作。在iOS7上,必须重写TextField类和

    - (void) drawPlaceholderInRect:(CGRect)rect
    

    方法。

    这样地:

    - (void) drawPlaceholderInRect:(CGRect)rect
    {
        [[UIColor blueColor] setFill];
        CGRect placeholderRect = CGRectMake(rect.origin.x, (rect.size.height- self.font.pointSize)/2, rect.size.width, self.font.pointSize);
        [[self placeholder] drawInRect:placeholderRect withFont:self.font lineBreakMode:NSLineBreakByWordWrapping alignment:self.textAlignment];
    }
    

    适用于iOS7和早期版本。

        3
  •  2
  •   diegosantiviago    9 年前

    我只使用了颜色,但我们还需要设置字体。

    这个对我有用:

    [[UITextField appearanceWhenContainedIn:[UISearchBar class], nil] setDefaultTextAttributes:
    @{
         NSForegroundColorAttributeName:[UIColor whiteColor], 
         NSFontAttributeName: [UIFont systemFontOfSize:12]
    }];
    
        4
  •  0
  •   mattsson    7 年前

    使用更改最小线高度 NSParagraphStyle

        NSMutableParagraphStyle *style = [self.addressBar.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    style.minimumLineHeight = self.addressBar.font.lineHeight - (self.addressBar.font.lineHeight - placeholderFont.lineHeight) / 2.0;
    
    self.addressBar.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder text" attributes:@{
         NSForegroundColorAttributeName: [UIColor colorWithRed:79/255.0f green:79/255.0f blue:79/255.0f alpha:0.5f],
         NSFontAttributeName : placeholderFont,
         NSParagraphStyleAttributeName : style
    }];