我正在尝试更改 Xcode IB 中标签的文本颜色。但是每次,背景也会改变,这很烦人。
http://screencast.com/t/XgyqQrLe4cmV
仅更改文本颜色的正确方法是什么?
界面生成器中应该有一个文本颜色框,但您也可以通过代码来完成。
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,100)]
label.textColor = [UIColor redColor];
或者只是使用您已经拥有的文本标签的引用。确保它是一个 IBOutlet 并在界面生成器中链接,尽管如果你在那里添加它。
您也可以将颜色更改为许多其他颜色:Apple 为此提供了很多便捷方法,例如您想要绿色文本,那么您可以使用 greenColor 便捷方法:
label.textColor = [UIColor greenColor];
有很多选择,以下是我在“UIColor.h”中找到的其他便捷方法:
+ (UIColor *)blackColor; // 0.0 white
+ (UIColor *)darkGrayColor; // 0.333 white
+ (UIColor *)lightGrayColor; // 0.667 white
+ (UIColor *)whiteColor; // 1.0 white
+ (UIColor *)grayColor; // 0.5 white
+ (UIColor *)redColor; // 1.0, 0.0, 0.0 RGB
+ (UIColor *)greenColor; // 0.0, 1.0, 0.0 RGB
+ (UIColor *)blueColor; // 0.0, 0.0, 1.0 RGB
+ (UIColor *)cyanColor; // 0.0, 1.0, 1.0 RGB
+ (UIColor *)yellowColor; // 1.0, 1.0, 0.0 RGB
+ (UIColor *)magentaColor; // 1.0, 0.0, 1.0 RGB
+ (UIColor *)orangeColor; // 1.0, 0.5, 0.0 RGB
+ (UIColor *)purpleColor; // 0.5, 0.0, 0.5 RGB
+ (UIColor *)brownColor; // 0.6, 0.4, 0.2 RGB
+ (UIColor *)clearColor; // 0.0 white, 0.0 alpha
另外,如果您想使用上述便捷方法中找不到的自定义颜色(例如 Hot Pink)为标签着色,我们可以这样做:255-105-180
label.textColor = [UIColor colorWithRed:(255.0/255.0) green:(105.0/255.0) blue:(180.0/255.0) alpha:1];//nice
我在这里找到了HOT Pink的 RGB 代码: http ://www.tayloredmktg.com/rgb/
另请注意,我将 RGB 值除以 255 以将它们标准化为 0 和 1。有关更多信息,请参阅此链接:Using [UIColor colorWithRed:green:blue:alpha:] doesn't work with UITableView seperatorColor?
我在 Xcode 5,部署目标 7.1 中对此进行了测试,我得到了 HOT PINK 文本!现在我已经为那个情人节应用程序做好了准备。你自己试试:)
当您单击 UI 中的颜色框时,您将看到它被选中。如果您没有看到它被选中,请再次单击它。当它没有被选中时,颜色会改变背景(如果你保持颜色选择器打开,这似乎是默认选择)。
很简单:
[self.lblValue setTextColor:[UIColor redColor]];