【问题标题】:IOS align text placeholder to be in the center and left alignmentIOS对齐文本占位符居中和左对齐
【发布时间】:2017-03-24 07:18:18
【问题描述】:

我正在创建一个提交反馈的 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];

}

但占位符文本位于垂直顶部。我们如何才能获得金牌。非常感谢

【问题讨论】:

  • rect 的值是多少,它是否覆盖了控件的整个高度?或者只是占位符文本的一行高度?
  • hi rect 是保持文本域的框架
  • 不会使用自动布局,UITextField 和 UITextField 的placeholder 属性更容易吗? UITextField 已经为您将文本垂直居中对齐。内阴影会是个问题,我不知道如何生成内阴影,我知道如何使用代码生成外阴影。
  • 嗨,它是一个没有情节提要或笔尖的旧项目。全部在代码中。 - (void)drawPlaceholderInRect:(CGRect)rect 是文本字段中的方法
  • 您不需要使用故事板或笔尖来进行自动布局。您可以纯粹在代码中完成。

标签: ios objective-c uitextfield placeholder


【解决方案1】:

您可以将占位符的“y”位置表示您的“rect”值作为文本字段高度/2。如果您使用文本字段的默认属性作为水平对齐的占位符,则还有一个解决方案。

喜欢:

var tt : UITextField
        tt.placeholder = ""

【讨论】:

  • 您好,您能详细解释一下我们如何实现它吗?谢谢
  • 您是如何通过情节提要或以编程方式使用文本字段的?
  • 我正在以编程方式使用(继承旧项目)
  • 你在哪里调用你的函数 - (void)drawPlaceholderInRect:(CGRect)rect {
  • 只要让你的 rect 值像这样
【解决方案2】:

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

- (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];
}

【讨论】:

  • 非常感谢您解决了这个问题。您认为文本字段的子类化是否可以让默认文本字段达到相同的结果?
  • 我认为是,您可以简单地使用UITextFieldattributedPlaceholder 属性。一定要试一试:)
猜你喜欢
  • 2016-09-24
  • 2013-12-21
  • 2015-04-08
  • 2014-10-29
  • 1970-01-01
  • 2019-10-01
  • 2018-05-21
  • 1970-01-01
  • 2016-02-13
相关资源
最近更新 更多