将UITapGestureRecognizer添加到XIB

时间:2016-02-01 03:18:04

标签: ios swift interface-builder uigesturerecognizer

我已经创建了一个从UITableViewHeaderFooterView扩展的自定义XIB,并尝试添加手势识别器。唯一的问题是尝试通过界面构建​​器添加识别器结果将对象添加到顶级层次结构中,以及导致我的应用程序崩溃的以下错误:

  

由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'为标识符注册的无效nib(AccordionHeader) - nib必须只包含一个必须是UITableViewHeaderFooterView实例的顶级对象'

据我所知,没有“viewDidLoad”等效可用,或者我只是以编程方式添加识别器。还有另一种方法吗?

2 个答案:

答案 0 :(得分:0)

你是对的,不能将识别器添加到顶层的XIB上。

我的解决方案如下:

class SettingsUserAvatarHeader: UITableViewHeaderFooterView {

    // Set as a variable, as it will be re-created on cell re-use
    var tapGestureRecognizer = UITapGestureRecognizer()

    // This will be called every time the cell moves off screen and returns 
    override func prepareForReuse() {
        super.prepareForReuse()

        // Needs to be done manually.
        tapGestureRecognizer = UITapGestureRecognizer()
        avatarImageView.gestureRecognizers = [ tapGestureRecognizer ]
    }

    // This will be needed for the first display
    override func didMoveToSuperview() {
        super.didMoveToSuperview()

        avatarImageView.gestureRecognizers = [ tapGestureRecognizer ]
    }
}

有了这个,你可以直接听取水龙头。我使用RxSwift:

首先,为点击添加扩展名:

extension Reactive where Base: SettingsUserAvatarHeader {

    var avatarTap: ControlEvent<UITapGestureRecognizer> {
        return self.base.tapGestureRecognizer.rx.event.asControlEvent()
    }

}

在你的控制器/委托等中:

class Consumer: UITableViewDelegate {

    var avatarTapDisposable: Disposable?

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "userAvatarView")
        let view = cell as! SettingsUserAvatarHeader

        avatarTapDisposable =
                view.rx
                    .avatarTap
                    .subscribe(onNext: { (tap) in
                        // Here your code for the tap
                    })

        return cell
    }
}

答案 1 :(得分:0)

尝试

步骤1:-注册XIB文件

func regXib(){
 self.tblList.register(UINib(nibName: "YourCellName", bundle: nil), forHeaderFooterViewReuseIdentifier: "YourCellNameIdentifierName")
}

步骤:-2 viewForHeaderInSection方法

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableHeaderFooterView(withIdentifier: "YourCellNameIdentifierName") as! YourCellName
        let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.expand))
        cell.layer.backgroundColor = UIColor.white.cgColor
        cell.addGestureRecognizer(recognizer)
        cell.tag = section
        return cell
    }

第3步:-点击手势操作

@objc func expand(sender:UITapGestureRecognizer){
   let tag = (sender.view?.tag)!
   // Tap Action Code Here 
}