UIButton的标题颜色在突出显示/选中时不会改变,但背景颜色会改变

Dav*_*ser 9 objective-c uibutton ios

这是一个非常奇怪的过程.

我有一个UIButtons的IBOutletCollection.我遍历集合并像这样创建它们(displayHourButtons从中调用viewWillAppear):

- (void)displayHourButtons
{
    // Counter
    NSUInteger b = 0;

    // Set attributes
    UIFont *btnFont = [UIFont fontWithName:@"Metric-Semibold" size:13.0];
    UIColor *btnTextColor = [UIColor colorWithRed:(147/255.0f) green:(147/255.0f) blue:(147/255.0f) alpha:1.0];
    NSNumber *btnTracking = [NSNumber numberWithFloat:0.25];
    NSMutableParagraphStyle *btnStyle = [[NSMutableParagraphStyle alloc] init];
    [btnStyle setLineSpacing:2.0];

    NSDictionary *btnAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
                              btnFont, NSFontAttributeName,
                              btnTextColor, NSForegroundColorAttributeName,
                              btnTracking, NSKernAttributeName, nil];

    // CREATE THE BUTTONS
    for (UIButton *hourButton in hourButtons) {
            // I'm using the attributed string for something else
            // later in development that I haven't got to yet. 
            // I simplified the string for this example's sake.
        NSString *btnTitleText = [NSString stringWithFormat:@"Button %lu", (unsigned long)b];

        NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]
                                                     initWithString:btnTitleText
                                                     attributes:btnAttrs];

        [attributedText addAttribute:NSParagraphStyleAttributeName
                               value:btnStyle
                               range:NSMakeRange(0, btnTitleText.length)];


        CALayer *btnLayer = [hourButton layer];
        [btnLayer setMasksToBounds:YES];
        [btnLayer setCornerRadius:19.0f];
        [hourButton setTag:b];
        [hourButton setContentEdgeInsets:UIEdgeInsetsMake(5.0, 1.0, 0.0, 0.0)];
        [hourButton setAttributedTitle:attributedText forState:UIControlStateNormal];
        [hourButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
        [hourButton setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
        hourButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
        [hourButton addTarget:self action:@selector(showHour:) forControlEvents:UIControlEventTouchUpInside]; 

        b++;
    }
}
Run Code Online (Sandbox Code Playgroud)

单击其中一个按钮时,将showHour:调用该操作:

- (IBAction)showHour:(id)sender
{
    [self.hourButtons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        UIButton *button = (UIButton *)obj;

        if (button != sender && button.enabled) {
                // This is applied. I know because I tested it with redColor
            [button setBackgroundColor:[UIColor clearColor]];

            // Doesn't change, stays the gray set initially
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }
        else {
                // This is applied
            [button setBackgroundColor:[UIColor colorWithRed:(169/255.0f) green:(234/255.0f) blue:(255/255.0f) alpha:1.0]];

            // This is not
            [button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal | UIControlStateSelected | UIControlStateHighlighted)];
        }
    }];

    // displayHour uses the tag to change labels, images, etc.
    [self displayHour:(long int)[sender tag]];
}
Run Code Online (Sandbox Code Playgroud)

我尝试了各种疯狂的事情让UIImage处于选定的状态,但没有任何效果.这个enumerateObjects交易是唯一有效的.这就是为什么我说这是一个奇怪的过程.我猜按钮不会无限期保持活跃状态​​?

无论如何,我的问题:标题颜色没有变化的原因有哪些?只是背景?我怀疑它与最初未设置的背景有关,但我无法解释原因.

谢谢!

更新

Per @Timothy Moose的回答,下面是更新后的代码.

- (IBAction)showHour:(id)sender
{   
    [self.hourButtons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        UIButton *button = (UIButton *)obj;

        // Grab the mutable string from the button and make a mutable copy
        NSMutableAttributedString *attributedText = [[button attributedTitleForState:UIControlStateNormal] mutableCopy];

        // Shared attribute styles
        UIFont *btnFont = [UIFont fontWithName:@"Metric-Semibold" size:14.0];
        NSNumber *btnTracking = [NSNumber numberWithFloat:0.25];
        NSMutableParagraphStyle *btnStyle = [[NSMutableParagraphStyle alloc] init];
        [btnStyle setLineSpacing:2.0];

        // Since we can't set a color directly on a Attributed string we have
        // to make a new attributed string.
        if (button != sender && button.enabled) {
            // Return to the default color
            UIColor *btnTextColor = [UIColor colorWithRed:(147/255.0f) green:(147/255.0f) blue:(147/255.0f) alpha:1.0];

            // Set up attributes
            NSDictionary *btnAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
                                      btnFont, NSFontAttributeName,
                                      btnTextColor, NSForegroundColorAttributeName,
                                      btnTracking, NSKernAttributeName, nil];

            // Reapply the default color (for the one button that was changed to white)
            [attributedText setAttributes:btnAttrs
                                    range:NSMakeRange(0, attributedText.length)];

            // Add line-height
            [attributedText addAttribute:NSParagraphStyleAttributeName
                                   value:btnStyle
                                   range:NSMakeRange(0, attributedText.length)];

            // Reset default attributes
            [button setBackgroundColor:[UIColor clearColor]];
            [button setAttributedTitle:attributedText forState:UIControlStateNormal];
        }
        else {
            // Our new white color for the active button
            UIColor *btnTextColor = [UIColor whiteColor];

            // Set up attributes
            NSDictionary *btnAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
                                      btnFont, NSFontAttributeName,
                                      btnTextColor, NSForegroundColorAttributeName,
                                      btnTracking, NSKernAttributeName, nil];

            // Apply our new white color
            [attributedText setAttributes:btnAttrs
                                    range:NSMakeRange(0, attributedText.length)];

            // Add line-height
            [attributedText addAttribute:NSParagraphStyleAttributeName
                                   value:btnStyle
                                   range:NSMakeRange(0, attributedText.length)];

            // Add new attributes for active button
            [button setBackgroundColor:[UIColor colorWithRed:(169/255.0f) green:(234/255.0f) blue:(255/255.0f) alpha:1.0]];
            [button setAttributedTitle:attributedText forState:UIControlStateNormal];
        }
    }];

    [self displayHour:(long int)[sender tag]];
}
Run Code Online (Sandbox Code Playgroud)

Cat*_*lin 19

同样重要的是不要在系统样式上使用按钮,只需将其置于自定义...这是针对类似问题,而不是针对此特定问题.

  • 系统样式按钮和自定义样式按钮之间的区别是什么?这方面的文件似乎含糊不清.首先,使其成为自定义样式会删除用作文本颜色的tintColor.还有什么其他差异?谢谢. (2认同)

Tim*_*ose 17

setTitleColor标题是属性字符串时没有任何效果.在将所需颜色应用于属性字符串后,使用普通NSStringsetAttributedTitle再次调用.