繁体   English   中英

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

[英]Switched from UILabel to UIButton. Text disappears

我刚刚从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];

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

我会欣喜若狂,因为我想使用这个功能。

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

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

然后使用:

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

必须具体控制状态( 突出显示选中等)

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

试试看,例如,

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


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM