簡體   English   中英

UICollectionViewCell 的便利初始化

[英]Convenience Init For UICollectionViewCell

我有一個自定義的UICollectionViewCell ,我在整個項目的兩個地方使用它。

除了顯示UIButton之外,兩個UICollectionViewCell是相同的。 為了減少代碼重復,我想在兩個地方都使用單元格,但用 Boolean 初始化一個單元格,以確定是否顯示按鈕。

我相信我需要一個便利的初始值設定項來執行此操作,但是,我收到了錯誤;

在“self.init”調用或賦值給“self”之前使用“self”

代碼

class MediaSelectionCell: UICollectionViewCell {
    
    var withDeleteButton = false
    
    convenience init(showsDeleteButton: Bool) {
        self.init(showsDeleteButton: withDeleteButton)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

任何幫助是極大的贊賞。

您的 collectionview 單元格初始化沒有名為self.init(showsDeleteButton: withDeleteButton)的方法,這就是您收到錯誤消息的原因。

正如評論中所說,細胞是可重復使用的。 如果您使用 storyboard 注冊單元格,則required init?(coder: NSCoder)初始化方法,如果您以編程方式注冊單元格,則會調用override init(frame: CGRect)

所以我的意思是,如果你使用dequeueReusableCell ,你不能手動更改初始化方法。

我更喜歡創建兩個類來做你想做的事:

一個不顯示按鈕:

class MediaSelectionCell: UICollectionViewCell {

var withDeleteButton = false
   
      override init(frame: CGRect) {
       super.init(frame: frame)
       // maybe adding constraint your bla bla
       
   }

   
   required init?(coder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }

   func controlButton() -> Bool{
      if withDeleteButton{
         // show
         return true
     }else{
         // hide
         return false
     }
  }
 }

一個用於顯示按鈕:

class MediaSelectionShowButton : MediaSelectionCell{
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.withDeleteButton = true
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

在你的牢房里,你可以控制它並做你想做的事:

cell.controlButton()

您不能對表視圖或集合視圖單元格使用便利初始化程序,因為表視圖/集合視圖通過調用指定的初始化程序來創建它們。

您必須向自定義 class 添加屬性並將其設置為支持該屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM