2017-01-16 92 views
1

我有一個奇怪的視圖出現在我的UICollectionViewCell子類中,有一個直觀的2個imageViews和1個按鈕的結構。從筆尖創建的UICollectionViewCell中的奇怪UIView

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

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個子視圖。 即使我停止執行調用之後:

(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>)>>" 

回答

2

這是電池的contentView - 看到documentation

您的子視圖應該被添加到contentView而不是直接在它們當前的單元格中。這是因爲你的筆尖是一個普通的UIView,它不包含contentView屬性。

你需要做的是用UICollectionViewCell對象設計你的筆尖,通過簡單的拖動相應的對象到界面生成器:

image

+0

這是有道理的。謝謝!有沒有適當的方法來設置筆尖細胞更好地重複使用? – Yaroslav

+0

是的,只需刪除自動添加的模板'UIView',並從對象庫中拖拽** Collection View Cell **。之後,您可以像更改「UIView」一樣更改單元格的屬性並將其他對象添加到層次結構中。 – xoudini