从 nib 创建的 UICollectionViewCell 中的奇怪 UIView

Strange UIView in a UICollectionViewCell created from nib

我的 UICollectionViewCell 子类中出现了一个奇怪的视图,它具有 2 个图像视图和 1 个按钮的简单结构。

final class ProfileImageCell:UICollectionViewCell {
    static var name: String { return "ProfileImageCell" }
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var anotherImageView: UIImageView!
    func setup(...) { ... } 
    @IBAction func buttonAction(_ sender: UIButton) { ... }
}

在 setup() 方法中,我设置了 imageViews 并传递了一些属性。我不创建任何视图或更改自己的子视图。

然后在我的 viewcontroller 中像往常一样设置 collectionView。

collectionView.register(UINib(nibName: ProfileImageCell.name, bundle: nil), forCellWithReuseIdentifier: ProfileImageCell.name)

ProfileImageCell.xib

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProfileImageCell.name, for: indexPath) as! ProfileImageCell
    cell.setup(...)
    return cell
}

这是奇怪的事情发生的时候。我的单元格中有 4 个子视图。 即使我在调用后立即停止执行:

(lldb) po cell.subviews
▿ 4 elements
  - 0 : <UIImageView: 0x1026bac00; frame = (0 0; 375 667); autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x170236dc0>>
  - 1 : <UIImageView: 0x1026bade0; frame = (263 0; 112 112); autoresize = RM+BM; layer = <CALayer: 0x170237160>>
  - 2 : <UIButton: 0x1026ba4d0; frame = (263 0; 112 112); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x170237140>>
  - 3 : <UIView: 0x102732cb0; frame = (0 0; 600 600); gestureRecognizers = <NSArray: 0x17444e430>; layer = <CALayer: 0x174238aa0>>

有人知道 那个 UIView 可能来自哪里吗?它有一个奇怪的框架(在单元格出现在屏幕上后它不会改变),覆盖了我的所有单元格并且不让任何手势通过按钮。另外,非常有趣的是,为什么它有手势识别器?

(lldb) po cell.subviews[3].gestureRecognizers?.first?.description
▿ Optional<String>
  - some : "<UILongPressGestureRecognizer: 0x10271db10; state = Possible; view = <UIView 0x102732cb0>; target= <(action=_handleMenuGesture:, target=<Application.ProfileImageCell 0x1026ba790>)>>"

这是单元格的 contentView – 请参阅 documentation

您的子视图应该添加到 contentView 而不是直接添加到它们当前所在的单元格中。发生这种情况是因为您的笔尖是一个普通的 UIView,它不包含 contentView 属性.

您需要做的是使用 UICollectionViewCell 对象设计您的笔尖,只需将适当的对象拖到界面构建器中即可:

使用 XIB 文件创建一个 UICollection 视图单元格。当创建为 UIView 时,您不能将 UICollectionViewCell 拖放到 XIB 中。 New Arrival collection View Cell 是一个 XIB,但它的类型是 UICollectionViewCell。在第二张图片中 Product Collection View Cell 也是 XIB 用作 UICollectionViewCell 但其类型是 UIView。两者都是以两种方式创建的。

情况一:我们的UICollectionViewCell前面没有UIView

情况二:我们的UICollectionViewCell前面有UIView

确保您的 XIB 不是 UIView。