从UILabel切换到UIButton。文字消失了

时间:2014-05-11 22:14:21

标签: ios uibutton uilabel

我刚刚从UILabel切换到UIButton,打算使用按钮的titleLabel属性来显示以前显示在按钮替换的标签中的信息。 / p>

问题是,文字没有显示出来。我已经检查过按钮本身(通常是透明的背景,改为红色来检查)是否正在出现,而且它是,但文字不在那里。这是相关代码的示例,与标签中的原始(工作)代码相同,仅更改以下行:

UILabel *firstLabel;

(...)

firstLabel.textColor = [UIColor blackColor];

为:

UIButton *firstLabel;

(...)

firstLabel.titleLabel.textColor = [UIColor blackColor];

为了清晰起见,这里是一个完整的块:

         firstLabel.frame = CGRectMake(thisRiser.bounds.origin.x, thisRiser.frame.size.height -focusBarEndHeight - 55, barWidth, 60);
         firstLabel.backgroundColor = [UIColor clearColor];
         firstLabel.titleLabel.textColor = [UIColor blackColor];
         firstLabel.titleLabel.text = [NSString stringWithFormat:@"%@\n%.2f%%\nTime--%@",focusItemName,focusItemPercent,actualDurationFocusItem];
         [firstLabel.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
         firstLabel.titleLabel.numberOfLines = 0;
         firstLabel.titleLabel.textAlignment = NSTextAlignmentCenter;
         [firstLabel setHidden:NO];

我错过了什么?有什么想法吗?

谢谢!

更新 - 这可能与已知错误有关!

非常感谢下面的响应者。我实现了第一个推荐的修复程序,它解决了我的初始问题,所以我的文本现在出现在标签中。但是,UIControlStateHighlighted和UIControlStateSelected不起作用。

例如,此代码在单击时不会对文本产生明显影响:

firstLabel.backgroundColor = [UIColor clearColor];
[firstLabel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[firstLabel setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[firstLabel setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];

在搜索了一段时间之后,我得出的结论是,有一个错误(至少在iOS 7中)阻止了这些方法的正常运行。不幸的是,我不够聪明,无法提供更详细的信息,但最近的大量帖子都指出了UIControl这个领域的一个主要问题。

我会因为被证明是错误而欣喜若狂,因为我想使用这个功能。

3 个答案:

答案 0 :(得分:1)

要在UIButton中设置标题,您必须初始化按钮:

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 60, 20)];

然后使用:

[button setTitle:@"text" forState:UIControlStateNormal];

必须具体控件状态(突出显示选择等)

答案 1 :(得分:1)

UIButton会响应不同的消息,您可以使用按钮状态更改其标题。

您可以像这样设置标题;

UIButton *button = [UIButton buttonWithType: UIButtonTypeCustom];
[button setTitle:@"Title goes here" forState:UIControlStateNormal];

请参阅控制状态:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIControl_Class/Reference/Reference.html#//apple_ref/c/tdef/UIControlState

答案 2 :(得分:0)

尝试例如,

UIButton *firstLabel = [UIButton buttonWithType:UIButtonTypeCustom];
firstLabel.frame = CGRectMake(0, 60, 100, 50); //set the frame
[firstLabel setTitle:@"Hello" forState:UIControlStateNormal];
[firstLabel setBackgroundColor:[UIColor redColor]];//for test
[firstLabel setTitleColor:[UIColor greenColor] forState:UIControlStateNormal]; //it will always displays green for normal
[firstLabel setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];//if u touch it text changed to white instantly
[firstLabel setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];//if touch it and hold it shows white color