22

我无法UITextField用 a控制 a 的背景颜色borderStyle= UITextBorderStyleRoundedRect。使用这种边框样式,该backgroundColor属性似乎只能控制圆角矩形内边缘的一条非常窄的线。该字段的其余部分保持白色。

但是,如果borderStyle设置为UIBorderStyle=UITextBorderStyleBezel则整个背景UITextField由其backgroundColor属性控制。

这是一个功能吗?有没有办法用 a控制backgroundColora ?UITextFieldborderStyle=UITextBorderStyleRoundedRect

4

7 回答 7

34

要更改 UITextField 中的背景颜色,您首先需要在 Interface Builder 中或以编程方式使用与“圆形”样式(例如“无边框”样式)不同的文本字段样式。

然后,您可以轻松地更改背景颜色

textField.backgroundColor = backgroundColor;

其中 textField 是您的 UITextField,backgroundColor 是 UIColor。

作为进一步的提示 - 如果您希望恢复圆角外观,您首先需要

#import <QuartzCore/QuartzCore.h>

然后设置

textField.layer.cornerRadius=8.0f;
textField.layer.masksToBounds=YES

为使此功能起作用

于 2010-11-19T00:24:44.830 回答
14

使用覆盖的彩色 UITextField

其他答案在具有圆角矩形样式的 UITextField 上没有阴影。在尝试了许多选项后,我终于在 UITextField 上放置了一个 UIView,具有相同的框架和自动调整大小的蒙版,将 alpha 设置为 0.3,并将背景设置为蓝色。然后我使用 Peter Johnson 的答案片段将圆形边缘从彩色叠加视图中剪掉。此外,取消选中 IB 中的“启用用户交互”复选框,以允许触摸事件向下级联到下面的 UITextField。现在看起来很完美。

副作用:您的文本也将被着色(不管它是否为黑色)

#import <QuartzCore/QuartzCore.h>

colorizeOverlayView.layer.cornerRadius = 6.0f;
colorizeOverlayView.layer.masksToBounds = YES;
于 2011-11-22T21:51:23.797 回答
6

这比我们想象的要容易得多。

当使用 colorWithRed:green:blue: 设置背景颜色时,颜色应该是浮动的并且应该是 1 的小数。例如:

[myTextField setBackgroundColor:[UIColor colorWithRed:255.0f/255.0f green:110.0f/255.0f blue:110.0f/255.0f alpha:1];

执行此操作时,所有 TextField 样式似乎都有效。

另请参阅:背景颜色未按预期工作

于 2012-07-20T21:41:07.873 回答
4

视图层次结构的转储显示UITextField有一个类型为 的子视图UITextFieldRoundedRectBackgroundView,而该子视图又具有 12UIImageView秒。

Erica Sadun 的一篇较早的文章显示了一个附加UILabel的 ,Apple 显然在更高版本的 SDK 中删除了它。

摆弄UIImageViews 并没有太大变化。

所以答案是:可能没有办法改变背景颜色。

于 2009-12-28T21:54:13.593 回答
3

雅各布的答案是这里最好的答案,因为它允许您将阴影保留在 RoundedRect 文本框下方,所以雅各布+1!

要详细说明他的解决方案,您需要这样做:

    UIView *textFieldShadeView=[[UIView alloc] init];
[textFieldShadeView setFrame:myTextFiled.frame];
textFieldShadeView.layer.cornerRadius=8.0f;
textFieldShadeView.layer.masksToBounds=YES;
textFieldShadeView.backgroundColor=[UIColor blueColor];
textFieldShadeView.alpha=0.3;
textFieldShadeView.userInteractionEnabled=NO;
[self.view addSubview:textFieldShadeView];
[textFieldShadeView release];

myTextFiled 是您尝试更改背景颜色的圆角矩形文本字段。执行上述操作,您将获得 Jacob 的蓝色文本字段以及相应的阴影。

于 2011-12-24T20:16:14.463 回答
1
...
textField.opaque = YES;
textField.backgroundColor=[UIColor blueColor];
textField.layer.cornerRadius=8.0f;
textField.layer.masksToBounds=YES
于 2012-05-23T12:28:00.923 回答
0

你可以这样做:

textField.backgroundColor = [UIColor whiteColor];

在这种情况下,我用白色来做,但你可以用另一种颜色来做uiColor

希望它有帮助

于 2010-04-27T19:10:19.423 回答