objective-c - UIButton 上的两行文本各有不同的字体

标签 objective-c ios

我找到了一种在 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/

相关文章:

objective-c - 如何在 Mojave 中为我的应用禁用暗模式?

ios - OpenGL photoshop 叠加混合模式

ios - 每次用户点击图像时,在可缩放的 UIImageView 上绘制一个小方 block 。并缩放正方形

objective-c - Objective-C ,NSMutableDictionary 引用计数

objective-c - 归档多个项目

iOS屏幕一点点变黑

ios - 在不改变框架的情况下旋转 UIView

ios - 如何使单元格中的 UIButton 在被点击后立即保留特定状态?

php - xcode 6.1 更新后 xCode 无法连接到本地主机

ios - 你的 plist 应该包含 <string></string> 吗?