簡體   English   中英

如何從情節提要中的自定義視圖制作@IBAction?

[英]How to make @IBAction from a custom view in storyboard?

我在viewController添加了一個帶有按鈕的自定義視圖。 我想打一個@IBAction從按鈕到我viewController 我有以下問題:

  1. 如何使其顯示在情節提要中? 當我運行該應用程序時,它運行良好。
  2. 如何讓我的@IBAction從按鈕到我viewController
    class CustomCellView: UIView{    
      //MARK: Initializer

      override func awakeFromNib() {
          super.awakeFromNib()
      }

      override init(frame: CGRect) {
          super.init(frame: frame)
          commonInit()
      }
      required init?(coder: NSCoder) {
          super.init(coder: coder)
          commonInit()
      }

      override func prepareForInterfaceBuilder() {
          super.prepareForInterfaceBuilder()
          commonInit()
      }

     //MARK: Functions

      func commonInit(){
          let customView = Bundle.main.loadNibNamed("customCellView", owner: self, options: nil)?.first as? UIView ?? UIView()
          customView.frame = self.bounds
          self.addSubview(customView)
      }
    }

在添加了@objcviewController中添加customView

  • 例如
    @objc func actionCustom()
    {
        print("Click Added") 
    }
  • 采用
func commonInit(){
      let customView = Bundle.main.loadNibNamed("customCellView", owner: self, options: nil)?.first as? UIView ?? UIView()
      customView.frame = self.bounds
      self.addSubview(customView)

      customView.button.addTarget(self, action: #selector(actionCustom), for: .touchUpInside) //Add click code here
  }

  1. 我的customView沒有顯示在情節提要中,但是當我運行該應用程序時就可以了

    這是自定義視圖的預期行為。 您將不會看到僅在定義視圖的xib中使用自定義視圖的xib中的視圖外觀。

  2. 如何使@IBAction從該按鈕到我​​的viewController。

    你不能 自定義視圖不會在界面生成器中公開子視圖。 最好的辦法是使用委托模式,或者正如Bhavesh Sarsawa指出的那樣,通過將vc添加為目標,或者通過在ccustom視圖中創建IBAction來調用該模式,以調用依賴注入發送的閉包。

customButton.setAction { code that gets called when the button is pressed }

暫無
暫無

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

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