iPhone的UITextField背景颜色

我无法使用borderStyle= UITextBorderStyleRoundedRect来控制UITextField的背景颜色。 使用这种边框样式, backgroundColor属性似乎只能控制沿圆angular矩形内边缘的非常窄的线条。 其余的领域仍然是白色的。

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

这是一个function吗? 有没有办法来控制borderStyle=UITextBorderStyleRoundedRectUITextField borderStyle=UITextBorderStyleRoundedRect

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

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

 textField.backgroundColor = backgroundColor; 

其中textField是你的UITextField,而backgroundColor是一个UIColor。

作为更进一步的提示 – 如果你想恢复圆angular的外观,你将首先需要

 #import <QuartzCore/QuartzCore.h> 

然后设置

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

为此function工作

彩色的UITextField使用覆盖

其他答案没有圆angular矩形样式的UITextField上存在的阴影。 在尝试了很多选项之后,我终于在UITextField上放置了一个UIView,使用相同的帧和自动resize的蒙版,将alpha设置为0.3,并将背景设置为蓝色。 然后,我使用Peter Johnson的答案将彩色覆盖视图的圆形边缘剪下。 另外,取消IB中的“User Interaction Enabled”checkbox,允许触摸事件级联到下面的UITextField。 现在看起来很完美。

副作用:您的文字也会被着色(如果是黑色则无所谓)

 #import <QuartzCore/QuartzCore.h> colorizeOverlayView.layer.cornerRadius = 6.0f; colorizeOverlayView.layer.masksToBounds = YES; 

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

当使用colorWithRed:green:blue:设置backgroundColor时,颜色应该是浮点数并且应该是1的一部分。例如:

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

当你这样做时,所有的TextField样式似乎都可以工作。

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

视图层次结构的转储显示UITextField有一个types为UITextFieldRoundedRectBackgroundView子视图,而UITextFieldRoundedRectBackgroundView又有12个UIImageView

Erica Sadun的一篇较旧的文章展示了一个额外的UILabel ,苹果显然在SDK的更高版本中删除了这个UILabel

摆弄UIImageView并没有太大的改变。

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

雅各布的答案是最好的答案,因为它可以让你保持在RoundedRect文本框下的阴影,所以雅各!

为了阐述他的解决scheme,你需要做到这一点:

  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是您正在尝试更改背景色的圆angular矩形文本字段。 做到上述,你会得到雅各布的蓝色文字字段与适当的阴影。

 ... textField.opaque = YES; textField.backgroundColor=[UIColor blueColor]; textField.layer.cornerRadius=8.0f; textField.layer.masksToBounds=YES 

你可以这样做:

 textField.backgroundColor = [UIColor whiteColor]; 

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

希望它有帮助