【问题标题】:Make only specific area of UITableViewCell trigger cell selection仅使 UITableViewCell 触发单元格选择的特定区域
【发布时间】:2017-09-16 14:35:30
【问题描述】:

我有一个相当高的 UITableViewCell,上面有很多标签和按钮,我只希望标签/按钮未覆盖的某个区域(大约右上角)成为触发单元格选择状态的东西(那里会有一个复选框,用户会很清楚)。我想使用默认的UITableViewCell 选择,因为它处理子视图的背景等,因为我需要单元格的点击状态以将整个单元格显示为浅蓝色。

我尝试在我的标签和按钮后面放置一个没有任何作用的大按钮来“掩盖”一个区域,这在您实际点击按钮本身的某些地方有效,但是如果您点击一个标签在它后面的按钮,单元格仍然会消耗该点击并且单元格会突出显示。奇怪的是,水龙头没有转到中间的按钮。

如何拦截点击并确保只有在特定区域内表格视图才会获得该点击并触发单元格突出显示?

【问题讨论】:

  • 您尝试过使用 selection = .none 并自己处理单元格中的选择吗?
  • @ReinierMelian 是的,但是如前所述,我需要使用表格视图的默认选择,它会遍历所有子视图,将标签背景设置为清除等,这样您就可以看到单元格的选择视图。跨度>
  • 检查我的答案,测试它并让我知道@Sencha
  • @ReinierMelian 有趣的方法,我会测试一下,祈祷——谢谢!

标签: ios uitableview cocoa-touch


【解决方案1】:

听起来您想避免在用户点击您单元格中的某些视图时调用[UITableViewDelegate tableView:didSelectRowAtIndexPath:]。我建议通过在 UITableViewCell 子类中覆盖 [UIView hitTest:withEvent:] 来实现这一点。 [UIView hitTest:withEvent:]的默认返回值定义如下

当前视图最远的后代并包含点的视图对象。如果该点完全位于接收者的视图层次结构之外,则返回 nil。

因此,通过覆盖它并返回一个备用 UIView 实例(您的子视图的一个实例)而不是 UITableViewCell 实例,我们可以让 TableViewController 相信您在做除 UITableViewCell 实例之外的其他事情.

一个例子如下(我对 Swift 的了解非常有限。我的应用程序。):

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
     // suppose you put all your subviews in contentView
    for (UIView *subview in self.contentView.subViews) {
        // translates the point relative to the subviews coordinate system.
        CGPoint convertedPoint = [self convertPoint:point toView:subview]; 
        // returns the subview instance if the touch happens inside the subview.
        if (CGRectContainsPoint(subview.bounds, convertedPoint)) { 
            return subview;
        }
    }
    // call the super's implementation if you find the touch didn't hit any sub view
    return [super hitTest:point withEvent:event]; 
}
        

【讨论】:

    【解决方案2】:

    如果您在需要执行选择操作的部分中使用UIButton,并且在您的单元格中添加此实现必须按照您的需要工作

    示例代码

    import UIKit
    
    class OnlySelectablePartTableViewCell: UITableViewCell {
    
        override func awakeFromNib() {
            super.awakeFromNib()
            // Initialization code
        }
        //Action linked to the button for valid selection part of your cell
        @IBAction func selectionAction(_ sender: Any) {
            self.selectionStyle = .blue
            self.setSelected(!self.isSelected, animated: true)
        }
    
        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
            if(!selected)
            {
                self.selectionStyle = .none
            }
            // Configure the view for the selected state
        }
    
    }
    

    【讨论】:

    • @Sencha 你终于测试我的答案了吗?请提供一些反馈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多