从uiabel切换到UIButton.文字就消失了



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

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

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];

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

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

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

你可以这样设置标题;

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

参见ControlState: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIControl_Class/Reference/Reference.html#//apple_ref/c/tdef/UIControlState

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

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

,然后使用:

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

其中必须指定控件状态(高亮显示选中等)

尝试

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


最新更新