繁体   English   中英

需要在 iOS 中垂直居中自定义 UITextField 中的占位符文本

[英]Need to center placeholder text in custom UITextField vertically in iOS

我正在开发一个 iOS 应用程序,我在其中对 UITextField 进行了子类化,以设置占位符文本的颜色。 我也将它水平居中,但我的问题是我的占位符文本没有垂直居中,出于某种原因,光标没有在占位符文本内居中,而是出现在占位符文本的第一个字符之后。

我在 UITextField 子类中的方法我重写以设置占位符文本的颜色并使文本水平居中,如下所示:

- (void)drawPlaceholderInRect:(CGRect)rect {
    // Set colour and font size of placeholder text
    [[UIColor whiteColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:28] lineBreakMode:UILineBreakModeMiddleTruncation alignment:NSTextAlignmentCenter];

}

这是我创建和设置 UITextField 的代码:

_field = [[CustomTextField alloc] initWithFrame:CGRectMake(190, 300, 644, 64)];
_field.delegate = (id)self;
[_field becomeFirstResponder];
[_field setBackgroundColor:[UIColor darkGrayColor]];
[_field setTextColor:[UIColor whiteColor]];
[_field setPlaceholder:@"Enter First and Last Name"];
[[_field layer] setMasksToBounds:8.0f];
[[_field layer] setBorderColor:[[UIColor grayColor] CGColor]];
[[_field layer] setBorderWidth:1.0f];
[_field setFont:[UIFont fontWithName:@"Arial" size:25]];
[_field setReturnKeyType:UIReturnKeyDone];
[_field setTextAlignment:NSTextAlignmentCenter];
_field.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self.view addSubview:_field];

我最初将 UITextField 子类化,因为虽然一切看起来都很好,但由于某种原因,我的占位符文本是灰色而不是白色(我将其设置为文本字段的文本颜色)。 具有讽刺意味的是,占位符文本垂直和水平居中,并且光标居中。 所以为了更正占位符文本颜色,我将 UITextField 子类化,只是为了现在打开更多问题。

有没有一种方法可以让我现在垂直居中占位符文本,也可以将光标居中? 更好的是,有没有办法让我将占位符文本的灰色更改为白色而不必对其进行子类化? 这将是理想的。

我认为您忘记在 .h 中实现(而不是在您的自定义 TextField 类中)

@interface YourView : UIView<UITextFieldDelegate>

并且没有调用委托方法! 占位符 textcolor 必须是你想要的颜色,如果你这样做的话。

#import "YourView.h"

@implementation YourView

// .....

_field.delegate = self;
_field.textAlignment = NSTextAlignmentCenter;
// ....

您可以像这样添加一些垂直填充:

UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 30)];
_field.leftView = paddingView;
_field.leftViewMode = UITextFieldViewModeAlways;

来自苹果开发者库:

leftView 显示在文本字段左侧的叠加视图。

@property(nonatomic, retain) UIView *leftView

讨论 您可以使用左侧叠加视图来指示文本字段的预期行为。 例如,您可以在此位置显示放大镜以指示文本字段是搜索字段。

左覆盖视图放置在接收器的 leftViewRectForBounds: 方法返回的矩形中。 与此属性关联的图像应适合给定的矩形。 如果它不适合,则将其缩放以适合。

如果您的覆盖视图不与任何其他同级视图重叠,它会像任何其他视图一样接收触摸事件。 如果您为视图指定一个控件,该控件将照常跟踪和发送操作。 但是,如果覆盖视图与清除按钮重叠,则清除按钮始终优先接收事件。

链接到苹果开发者库/ UITextField

我希望这有帮助 !

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM