【问题标题】:iOS, objective C, referencing a button by tagiOS,目标 C,按标签引用按钮
【发布时间】:2014-03-20 01:55:24
【问题描述】:

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

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]];

}

那么如何通过标签改变按钮的背景呢?

谢谢!

【问题讨论】:

  • 是否有任何按钮获得背景颜色或没有任何反应?
  • 您正在向按钮对象询问 viewWithTag,即您正在向一个按钮询问与标签匹配的子视图!如果你用viewWithTag查询按钮的父视图,你会找到你要找的按钮。

标签: ios tags


【解决方案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]];

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多