11

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

我有一个 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++;
    }
}

单击其中一个按钮时,将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]];
}

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

无论如何,我的问题:标题颜色没有改变是否有某种原因?只是背景?我怀疑这与最初没有设置背景有关,但我无法解释原因。

谢谢!

更新

根据@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]];
}
4

6 回答 6

20

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

于 2014-01-31T02:11:47.137 回答
19

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

于 2013-10-06T03:51:03.790 回答
3

我创建了一个自定义类MyButton扩展自UIButton. 然后在里面添加这个Identity Inspector

在此处输入图像描述

在此之后,将按钮类型更改为Custom

在此处输入图像描述

然后,您可以为不同的状态设置类似textColorUIFont的属性:UIButton

在此处输入图像描述

然后我还在类中创建了两个方法,当我希望将 a显示为突出显示MyButton时,我必须在代码中调用它们:UIButton

- (void)changeColorAsUnselection{
    [self setTitleColor:[UIColor colorFromHexString:acColorGreyDark] 
               forState:UIControlStateNormal & 
                        UIControlStateSelected & 
                        UIControlStateHighlighted];
}

- (void)changeColorAsSelection{
    [self setTitleColor:[UIColor colorFromHexString:acColorYellow] 
               forState:UIControlStateNormal & 
                        UIControlStateHighlighted & 
                        UIControlStateSelected];
}

您必须titleColor为 normal、highlight 和 selected设置,UIControlState因为根据文档,一次可以有多个状态UIControlState。如果您不创建这些方法,UIButton将显示选择或突出显示,但它们不会留在UIColor您设置的内部,UIInterface Builder因为它们仅可用于选择的简短显示,而不是用于显示选择本身。

于 2015-05-08T09:10:47.573 回答
0

就我而言,我使用的是 XCode 7.x。

我遇到了类似的问题。使用 NSAttributedString 后

let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
        let underlineAttributedString = NSAttributedString(string: "FILTER", attributes: underlineAttribute)
        filterButton.setTitleColor(AppConfig.FOREGROUND, forState: .Normal)
        filterButton.setAttributedTitle(underlineAttributedString, forState: .Normal)

filterButton.setTitleColor(AppConfig.FOREGROUND, forState: .Normal) 没有生效。

我在 Interface Builder 中更改了按钮的 Tint Color(默认为浅蓝色)。现在,它现在对我有用。

于 2015-10-05T23:42:59.550 回答
0

上述答案的替代方法是使用字符串属性应用文本颜色。您可以为每个控件状态设置不同的 NSAttributedString,这样可以达到相同的效果 - 按钮文本将在选择/突出显示时改变颜色。

例子:

// We're assuming attributedString already exists - this is your completed attributed string so far
// We're going to copy this string into two more NS(Mutable)AttributedString variables - one for the "normal" state and one for the "highlighted" state
NSMutableAttributedString *normalAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
// Set the desired foreground color (in this case it's for the "normal" state) for the length of the string
[normalAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,attributedString.length)];

// Rinse and repeat for the highlighted state
NSMutableAttributedString *highlightedAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
[highlightedAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,attributedString.length)];

// Finally, we'll set these as the attributedTitles for the relevant control states.
[myButton setAttributedTitle:normalAttributedString forState:UIControlStateNormal];
[myButton setAttributedTitle:highlightedAttributedString forState:UIControlStateSelected];
[myButton setAttributedTitle:highlightedAttributedString forState:UIControlStateHighlighted];
于 2015-12-15T06:19:14.427 回答
-2

我立刻注意到了这一点。可能只是一个简单的错误:)

改变

UIColor *btnTextColor = [UIColor colorWithRed:(147/255.f) 
                                        green:(147/255.f) 
                                         blue:(147/255.f) alpha:1.0];

UIColor *btnTextColor = [UIColor colorWithRed:(147/255.0f) 
                                        green:(147/255.0f) 
                                         blue:(147/255.0f) alpha:1.0];

它没有改变的原因可能是因为它没有识别出UIColor你在分区中没有完整的数字,因为它看到的是(147/255.)而不是(147/255.0)

于 2013-10-06T02:19:23.947 回答