UIButton每行都有不同的颜色文本

时间:2012-06-20 10:10:42

标签: uibutton

我想要一个带有两行文字的UIButton,每行都有不同的颜色。是否有可能这样?

5 个答案:

答案 0 :(得分:1)

我能想到两种方法:

方法1(简单):将其设为图像按钮

方法2(硬):使用2个单独的UILabel制作自定义UIButton,以便为它们配置不同的颜色

要实现方法2,首先要创建一个以UIButton为超类的类。然后,覆盖- (void)drawRect方法。为了不在SO中重复回答,请阅读:How to override -drawrect in UIButton subclass?

答案 1 :(得分:1)

您好这个答案仅适用于以上ios 6 ...

使用ios 6的归属文字来实现这一目标......

NSString* infoString=@"This is an example of Attributed String";

    NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString];
    NSInteger _stringLength=[infoString length];

    UIColor *_red=[UIColor redColor];
    UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:20.0f];
    [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, _stringLength)];
    [attString addAttribute:NSForegroundColorAttributeName value:_red range:NSMakeRange(0, _stringLength/2)];
    [self.attribButton setAttributedTitle:attString forState:UIControlStateNormal];
    self.attribButton.titleLabel.numberOfLines=2; 

试试这个......

答案 2 :(得分:1)

In Swift

var main_string = "Hello World"
var string_to_color = "World"
var range = (main_string as NSString).rangeOfString(string_to_color)
var attributedString = NSMutableAttributedString(string:main_string)
        attributedString.addAttribute(NSForegroundColorAttributeName, value: appSingleton.appRedColor , range: range)
self.celciusButton.setAttributedTitle(attributedString, forState: UIControlState.Normal)

答案 3 :(得分:0)

是的确定.. !!!制作一个你想要展示的图像然后将图像设置为该按钮的背景..!简单......

答案 4 :(得分:0)

  1. 首先,按下“自定义”类型的按钮。如果您需要以编程方式执行此操作:

    UIButton * myButton = [UIButton buttonWithType:UIButtonTypeCustom];

    myButton.frame = CGRectMake(x,y,width,height);

  2. 现在制作标签:

    UILabel * line1 = [[UILabel alloc] initWithFrame:CGRectMake(0,0,buttonWidth,buttonHeight / 2)];

    UILabel * line2 = [[UILabel alloc] initWithFrame:CGRectMake(0,buttonHeight / 2,buttonWidth,buttonHeight / 2)];

  3. 并指定所需的文字颜色:

    line1.textColor = [UIColor blueColor];

    line2.textColor = [UIColor redColor];

  4. 然后将标签添加到按钮,按钮添加到视图中:

    [myButton addSubview:line1];

    [myButton addSubview:line2];

    [self.view addSubview:myButton]; //仅当您以编程方式创建按钮时