【问题标题】:automatically set selected UIbutton highlighted in XCode?自动设置在 XCode 中突出显示的选定 UI 按钮?
【发布时间】:2012-10-11 10:15:42
【问题描述】:

我在 UITableViewCell 中显示一个 NSMutableArray 项目,其行为类似于 gridview。单元格中有自定义 UI 按钮。现在,当用户单击一个按钮时,我希望它突出显示。但是当我这样做时,发生的事情是当我单击一个按钮,它的颜色变为红色。但是当我单击下一个按钮时,它的颜色也变为红色,但前一个按钮的颜色也是红色。我希望前一个按钮保持未突出显示,当前按钮突出显示。我该怎么做? 这是我的代码:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 CGRect rect = CGRectMake(18+80*j, yy,57, 40);
        UIButton *button=[[UIButton alloc] initWithFrame:rect];
        [button setFrame:rect];

        [button setContentMode:UIViewContentModeCenter];
        NSString *settitle=[NSString stringWithFormat:@"%@",item.title];
        [button setTitle:settitle forState:UIControlStateNormal];
        NSString *tagValue = [NSString stringWithFormat:@"%d%d", indexPath.section+1, i];
        button.tag = [tagValue intValue];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];              
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [hlcell.contentView addSubview:button];
        [button release];
}

-(IBAction)buttonPressed:(id)sender {
int tagId = [sender tag];
int divNum = 0;
if(tagId<100)
    divNum=10;
else 
    divNum=100;
int section = [sender tag]/divNum;
section -=1; 
int itemId = [sender tag]%divNum;
UIButton *button = (UIButton *)sender;
if(button.enabled==true)

{
   button.backgroundColor=[UIColor redColor];
}

NSLog(@"…section = %d, item = %d", section, itemId);
NSMutableArray *sectionItems = [sections objectAtIndex:section];
Item *item = [sectionItems objectAtIndex:itemId];
NSLog(@"..item pressed…..%@, %@", item.title, item.link);

}

我该怎么做?

【问题讨论】:

  • 在 ibaction 方法中单击按钮时无法更改按钮
  • 对不起,我没有收到你。你能简单解释一下吗
  • 您已经采取行动,我们正在更改背景颜色,而不是更改该特定单元格处的按钮
  • 我对 Objective-C 很陌生。你能详细说明一下,告诉我代码的想法吗

标签: ios xcode uitableview uibutton


【解决方案1】:

一种方法是在头文件中为所有按钮保留一个 IBCollection 引用(将 Interface builder 中的所有按钮连接到此 IBOutletCollection):

@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *allOfMyButtons;

并且在您的 buttonPressed 方法中,仅当当前按下的按钮且该按钮已启用(所有其他按钮变回黑色或任何初始颜色)时,才将背景颜色设为红色:

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

        if (button != sender && button.enabled) {
            [button setBackgroundColor:[UIColor redColor]];
        } else {
            [button setBackgroundColor:[UIColor blackColor]];
        }
    }];
}

【讨论】:

  • 但我正在 UITableViewCell 中创建自定义 UIButton。在这种情况下,我无法将界面生成器中的所有按钮都连接到此 IBOutletCollection。所以我在该行收到此错误“程序收到信号”SIGABRT [self.allOfMyButtons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)。我该如何解决?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-23
  • 2017-10-16
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 2010-12-10
  • 2017-05-01
相关资源
最近更新 更多