【问题标题】:Why won't UITableCell immediately deselect when opening a URL in Safari?为什么在 Safari 中打开 URL 时 UITableCell 不会立即取消选择?
【发布时间】:2012-08-23 19:37:52
【问题描述】:

当触摸UITableViewCell 时,我有一个应用程序会关闭并转到 Safari 打开 URL。但是,当我返回应用程序时,仍会选择该单元格几秒钟。为什么不立即取消选择?它是一个错误吗?代码如下:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    if (indexPath.section == 0 && indexPath.row == 0) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.example.com/"]];
    }

}

我尝试将[tableView deselectRowAtIndexPath:indexPath animated:NO]; 移到顶部并关闭动画,但没有帮助。这没什么大不了的,但如果可能的话,我希望它立即取消选择。

UIButton 也会发生这种情况。返回应用程序后,它会保持突出显示状态一两秒。

【问题讨论】:

  • 你能发布更多代码吗

标签: objective-c ios uitableview


【解决方案1】:

[tableView deselectRowAtIndexPath:indexPath animated:NO]; 之类的更改会在运行循环的下一次迭代中生效。当您通过openURL: 退出时,会延迟下一次迭代,直到您切换回应用程序。切换回来是通过在您离开之前循环显示屏幕图像来实现的,然后几分钟后使应用程序再次交互。因此选择的图像仍然存在。

抛开实现的细节,逻辑是影响屏幕内容的事物被捆绑在一起并被原子化,这样当您进行视图调整时,您就不必一直想‘哦不,如果现在重新绘制框架,只完成到这里的更改?'。根据 iOS 多任务模型,在您返回应用程序之前不会发生调整界面的原子单元。

快速修复:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // deselect right here, right now
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    if (indexPath.section == 0 && indexPath.row == 0) {
        [[UIApplication sharedApplication]
                    performSelector:@selector(openURL:)
                    withObject:[NSURL URLWithString:@"http://www.example.com/"]
                    afterDelay:0.0];

        /*
              performSelector:withObject:afterDelay: schedules a particular
              operation to happen in the future. A delay of 0.0 means that it'll
              be added to the run loop's list to occur as soon as possible.

              However, it'll occur after any currently scheduled UI updates
              (such as the net effect of a deselectRowAtIndexPath:...)
              because that stuff is already in the queue.
        */
    }

}

【讨论】:

  • 哇,这真是一个有见地的解释和一个很好的解决方案。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 2017-12-19
  • 2021-01-10
  • 1970-01-01
  • 2020-12-04
  • 2021-11-08
相关资源
最近更新 更多