2017-07-17 61 views
-2

我在我的UIBarButton引用一個函數以繼承另一個視圖控制器的選擇器,但該函數在單擊時不會被調用。通過測試斷點,我可以看到函數segueToCartViewController永遠不會被調用。 在此先感謝!UIBarButtonItem中的選擇器沒有調用

的UIBarButtonItem初始化

private let reuseIdentifier = "ItemCell" 
private let SegueCartIdentifier = "CatalogToCart" 

final class CatalogViewController: UICollectionViewController { 
    //MARK: -properties 

    var brand: Brand! 
    var cart: [Item]! 

    fileprivate let itemsPerRow:CGFloat = 3 
    fileprivate let sectionInsets = UIEdgeInsets(top: 30, left: 20, bottom: 30, right: 20) 
    private var cartItem: UIBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "Cart"), style: .plain, target: self, action: #selector(segueToCartViewController(_:))) 

    var selectedItemIndexPath: IndexPath?{ 
     didSet{ 
      var indexPaths = [IndexPath]() 
      if let selectedItemIndexPath = selectedItemIndexPath{ 
       indexPaths.append(selectedItemIndexPath) 
      } 
      if let oldValue = oldValue{ 
       indexPaths.append(oldValue) 
      } 

      collectionView?.performBatchUpdates({ 
       self.collectionView?.reloadItems(at: indexPaths) 
      }) { completed in 
       if let selectedItemIndexPath = self.selectedItemIndexPath{ 
        self.collectionView?.scrollToItem(at: selectedItemIndexPath, at: .centeredVertically, animated: true) 
       } 
      } 
     } 
    } 

    override func viewDidAppear(_ animated: Bool) { 
     self.navigationController?.setToolbarHidden(false, animated: false) 
     let flex = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) 
     self.navigationController?.toolbar.items = [flex,cartItem,flex] 
    } 
} 

呼籲賽格瑞

//MARK: CartNavigation 
extension CatalogViewController: CartDelegate{ 

    func segueToCartViewController(_ sender: AnyObject){ 
     super.performSegue(withIdentifier: SegueCartIdentifier, sender: sender) 
    } 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     guard let destination = segue.destination as? UINavigationController else{ 
      return 
     } 

     cartVC.delegate = self 
    } 

    func closeModallyPresentedViewController() { 
     dismiss(animated: true, completion: nil) 
    } 
} 
+5

請將您的代碼發佈到文本中,而不是截圖 – PeejWeej

+2

請將您的代碼發佈到文本中,而不是截圖! –

回答

3

您的UIBarButtonItem的目標是零,因爲self爲零期間它的初始化。

你可以這樣來代替

final class CatalogViewController: UICollectionViewController { 
    lazy final private var cartItem: UIBarButtonItem = { [unowned self] in 
     return UIBarButtonItem(image: #imageLiteral(resourceName: <#T##String#>), style: .plain, target: self, action: #selector(segueToCartViewController(_:))) 
    }() 

    override function viewDidAppear(_ animated: Bool) { 
     //blah blah, the rest of your code 
    } 
} 

See here初始化有關的self性質的初始化過程中的價值一個很好的解釋。

+0

現在,我已經做到了該項目不可見。有任何想法嗎? @Allen Humphreys – Sak6lab

+0

如果我把代碼放在viewDidAppear函數中,按下按鈕應該工作的位置 – Sak6lab

+0

UIBarButtonItem不可見 – Sak6lab

相關問題