我有一个UIButton点击发件人,如下所示:-

-(IBAction)clipButtonClick:(UIButton *)sender
{
    sender.selected  = ! sender.selected;

    if (sender.selected)
    {
        [btnClipCategory setImage:[UIImage imageNamed:@"imgClip_HL"] forState:UIControlStateSelected];

        NSMutableArray* indexArray = [NSMutableArray array];
        for (NSInteger i = 0; i < self.arySubCategory.count; i++)
        {
            [aryCheckCategoryList replaceObjectAtIndex:i withObject:@"YES"];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [indexArray addObject:indexPath];

            dispatch_async(dispatch_get_main_queue(), ^{
                [self.rightTableView reloadData];
            });

        }

    }
    else
    {
        [btnClipCategory setImage:[UIImage imageNamed:@"imgClip"] forState:UIControlStateNormal];

        NSMutableArray* indexArray = [NSMutableArray array];
        for (NSInteger i = 0; i < self.arySubCategory.count; i++)
        {
            [aryCheckCategoryList replaceObjectAtIndex:i withObject:@"NO"];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [indexArray addObject:indexPath];



            dispatch_async(dispatch_get_main_queue(), ^{
                [self.rightTableView reloadData];

            });

        }

    }
}


当我单击按钮时,发件人将始终点击所选选项。

如果我将发件人更改为以下示例代码,我的应用程序将按预期正常运行。任何想法?请帮忙。谢谢。

-(IBAction)clipButtonClick:(UIButton *)sender
{
    sender.selected  = ! sender.selected;

    if (sender.selected)
    {
        [btnClipCategory setImage:[UIImage imageNamed:@"imgClip_HL"] forState:UIControlStateSelected];
        NSLog(@"Selected. Will Hit here");

    }
    else
    {
        [btnClipCategory setImage:[UIImage imageNamed:@"imgClip"] forState:UIControlStateNormal];
        NSLog(@"Non Selected. Will Hit here");

    }
}


已编辑
我将按钮放在willDisplayHeaderView下。

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{

    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;

    btnClipCategory = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnClipCategory setFrame:CGRectMake(header.frame.size.width - 45, header.frame.size.height * 0.2, ScreenW * 0.1, ScreenW * 0.1)];

    [btnClipCategory addTarget:self action:@selector(clipButtonClick:) forControlEvents:UIControlEventTouchUpInside];

    [header addSubview:btnClipCategory];

}

最佳答案

当您调用[self.rightTableView reloadData]时,将重新加载表视图的所有内容,包括节标题,并且为每个可见节标题调用tableView:willDisplayHeaderView:forSection:。因此,每次单击动作触发时,都会使用默认值bntClipCategory重新创建您的isSelected
您无需在工作代码示例中重新加载rightTableView,这就是它起作用的原因。

您应该重新考虑您的方法。选项之一是为数组中每个节保存按钮的isSelected状态,并在将其添加到标题视图之前相应地更新btnClipCategory.isSelected

关于ios - UIButton单击发件人始终转到所选选项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51529350/

10-13 03:55