我找到了一种在 UIButton 上添加两行文本的方法, 但我想要的是每一行文本 有不同的字体(例如一个是粗体,另一个不是)。 这怎么可能?
谢谢。
最佳答案
您应该将 2 个 UILabel 作为 subview 添加到 UIButton。
你可以这样做:
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeCustom];
testButton.frame = CGRectMake(0, 0, 200, 40);
[self.view addSubview:testButton];
UILabel *firstLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
firstLineTestButton.text = @"First line";
firstLineTestButton.font = [UIFont systemFontOfSize:12];
[testButton addSubview:firstLineTestButton];
UILabel *secondLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 200, 20)];
secondLineTestButton.text = @"Second line";
secondLineTestButton.font = [UIFont boldSystemFontOfSize:12];
[testButton addSubview:secondLineTestButton];
为了使 UILabel 也能突出显示,您需要自定义按钮的突出显示。
因此将操作添加到按钮,然后检查标签的按钮 subview 并更改它们的颜色。
[testButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[testButton addTarget:self action:@selector(changeColor:) forControlEvents:UIControlEventTouchDown];
[testButton addTarget:self action:@selector(touchCancel:) forControlEvents:UIControlEventTouchDragExit];
-(void)buttonAction:(UIButton*)sender
{
[self touchCancel:sender];
/* DO SOME MORE ACTIONS */
}
-(void)changeColor:(UIButton*)sender
{
sender.backgroundColor = [UIColor grayColor];
for( UIView *subview in sender.subviews ){
if( [subview isKindOfClass:[UILabel class]] ){
UILabel *subViewLabel = (UILabel*)subview;
subViewLabel.textColor = [UIColor blueColor];
}
}
}
-(void)touchCancel:(UIButton*)sender
{
sender.backgroundColor = [UIColor clearColor];
for( UIView *subview in sender.subviews ){
if( [subview isKindOfClass:[UILabel class]] ){
UILabel *subViewLabel = (UILabel*)subview;
subViewLabel.textColor = [UIColor blackColor];
}
}
}
关于objective-c - UIButton 上的两行文本各有不同的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13948582/