UIBarButtonItem中的选择器没有调用

时间:2017-07-17 20:59:53

标签: ios swift uibarbuttonitem

我的UIBarButton上有一个选择器,它引用一个函数来转换到另一个视图控制器,但是单击时函数永远不会被调用。通过测试断点,我可以看到函数segueToCartViewController永远不会被调用。 提前谢谢!

UIBarButtonItem init

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]
    }
}

要求segue

//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)
    }
}

1 个答案:

答案 0 :(得分:5)

您的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的值的详细说明。