ios - 从 nib 创建的 UICollectionViewCell 中的奇怪 UIView

标签 ios swift uicollectionview nib

我的 UICollectionViewCell 子类中出现了一个奇怪的 View ,它具有 2 个 ImageView 和 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 并传递了一些属性。我不创建任何 View 或更改自己的 subview 。

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

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

ProfileImageCell.xib

xib structure

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

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

(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 .

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

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

image

关于ios - 从 nib 创建的 UICollectionViewCell 中的奇怪 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41681319/

相关文章:

json - SwiftyJSON 极慢的 JSON 迭代

objective-c - 在 UITableViewController 中隐藏表行

ios - UICollectionViewDropDelegate 破坏了 UICollectionView 中的重新排序单元机制

ios - 如何构建连续视差滚动/ Collection View ?

ios - 使用表格数据进行 CoreML 设备端模型训练

ios - 单元格 ImageView 缩进

ios - 选择后 SwiftUI 选择器动画错误

ios - 使用 CoreData 时出现 NSFetchedResultsController fatal error (尝试获取)

ios - 我怎么知道 viewcontroller 是因为推送加载还是因为 UINavigationController 弹出后的 View 重建加载?

ios - UICollectionView 在某些单元格上重复标签和图像