由于更新到xcode 12,所以我无法在UITableViewCell内放置任何UIControl

问题描述

我有一个使用表格视图的搜索表单。今天更新Xcode 12之后,当嵌套在UITableViewCell中时,UISwitch,UITextField和UiSlider将不再起作用。是否需要更改一个属性才能使它再次起作用?

为确保这不仅仅是我的项目,我创建了一个新项目,并在其中嵌套了一个UITextField,它也不起作用。

override func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    
    let textField = UITextField(frame: CGRect(x: 5,y: 5,width: 400.0,height: 25.0))
    textField.delegate = self
    textField.backgroundColor = .blue
    cell.addSubview(textField)

    return cell
}

override func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
    print("this will get called even when selecting the UITextField")
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    print("this is never called")
}

解决方法

您的代码始终是错误的:

cell.addSubview(textField)

您必须从不将子视图添加到单元格。将子视图添加到单元格的contentView

,

自从我升级到iOS 14以来,我也发生了同样的事情。 当我将subViews直接添加到单元格时,这对我有用,

cell.contentView.isUserInteractionEnabled = true

,

有类似的问题,并且一直在解决……我的代码的问题是在UITableViewCell下我正在这样做:

        didSet {
            if contentView.backgroundColor == backgroundColor { return }
            contentView.backgroundColor = backgroundColor
            for v in otherView.subview { v.backgroundColor = backgroundColor }
        }

contentView.backgroundColor = backgroundColor处删除此行就可以了。单元格现在可见,没有重复的contentView

也许这会对某人有所帮助,因为我只找到了有关将子视图直接添加到cell而不是cell.contentView的答案

编辑1: 好的,只是想向您介绍最新情况,问题是我的子视图在UIStackView类型的地方,而我在实际上应该使用subview的地方使用了arrangedSubviews

希望这会对某人有所帮助