iOS,目标C,按标签引用按钮

时间:2014-03-20 01:55:25

标签: ios tags

我有一些根据数组创建的按钮

for (NSString *buttonTitle in buttons) {
    self.bottomOptionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.bottomOptionButton.frame = CGRectMake(xPos , buttonHeight , buttonWidth, buttonHeight);
    [self.bottomOptionButton setTitle:buttonTitle forState:UIControlStateNormal];
    [self.bottomOptionButton setTitleColor:[[ThemeManager shared]slipKeyboardFontColor] forState:UIControlStateNormal];
    self.bottomOptionButton.tag = index;
    [self.bottomOptionButton addTarget:self action:@selector(optionBottomButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.optionsKeyboard addSubview:self.bottomOptionButton];

    xPos += buttonWidth;
    index += 1;

    UIView *lowerVerticalLine = [[UIView alloc]initWithFrame:CGRectMake(xPos, buttonHeight, lineThickness, buttonHeight)];
    lowerVerticalLine.backgroundColor = [[ThemeManager shared]separatorLineColor];
    [self.optionsKeyboard addSubview:lowerVerticalLine];
}

它们被创建并显示正常,现在当点击一个按钮时,我可以得到按钮引用的标签,但是我需要按标签设置按钮的背景颜色,但是还没有工作

- (void)optionBottomButtonPressed:(id)sender
{
    UIButton *button = sender;

    NSLog(@"tu tag :: %d", button.tag);
    NSLog(@"de opcion :: %@", [self.bottomButtonArray objectAtIndex:button.tag] );

    UIColor *selectedButtonColor = [[ThemeManager shared]buttonSelectedBackground];
    UIColor *nonSelectedButtonColor = [UIColor whiteColor];

    for (int i = 0; i<= self.bottomButtonArray.count; i++) {

        UIButton *button = (UIButton *)[self.bottomOptionButton viewWithTag:i];
        button.backgroundColor = nonSelectedButtonColor;
    }

    [sender setBackgroundColor:[UIColor redColor]];

}

那么如何按标签更改按钮的背景?

谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个,

for (NSString *buttonTitle in buttons) {
    UIButton *bottomOptionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    ....
    bottomOptionButton.tag = index;
    ....
    [self.optionsKeyboard addSubview:bottomOptionButton];

    ....
}

并在optionBottomButtonPressed:

- (void)optionBottomButtonPressed:(id)sender
{
     NSLog(@"tu tag :: %d", button.tag);
     NSLog(@"de opcion :: %@", [self.bottomButtonArray objectAtIndex:button.tag] );

     UIColor *selectedButtonColor = [[ThemeManager shared]buttonSelectedBackground];
     UIColor *nonSelectedButtonColor = [UIColor whiteColor];

     for (int i = 0; i<= self.bottomButtonArray.count; i++) {

         UIButton *button = (UIButton *)[self.optionsKeyboard viewWithTag:i];
         button.backgroundColor = nonSelectedButtonColor;
     }

     [sender setBackgroundColor:[UIColor redColor]];

}