我有一个有一个按钮的视图控制器。当我单击该按钮时,我想将自定义视图(xib)作为子视图添加到视图控制器。在我的自定义视图(xib)中,我还有一个自定义委托和一个按钮。但是当我单击自定义视图(xib)中的按钮时,视图控制器中的委托方法永远不会被调用。
//View Controller
class BusinessMainViewController: UIViewController,BusinessSettingViewDelegate {
//MARK: - business setting view delegate
func businessSettingViewAction(settingView: BusinessSettingView, button: UIButton) {
switch button.tag {
case 100:
break
default:
break
}
settingView.removeFromSuperview()
}
//MARK: - Button action
@IBAction func settingAction(_ sender: UIButton) {
let settingView = BusinessSettingView.init(parentView: self.view)
settingView.delegate = self
settingView.showSetting()
}
}
//自定义视图+ xib:
+ xib name : BusinessSettingView.xib
+ custom view class: BusinessSettingView.swift
protocol BusinessSettingViewDelegate {
func businessSettingViewAction (settingView : BusinessSettingView, button : UIButton)
}
class BusinessSettingView: UIView {
var parentView : UIView!
var delegate : BusinessSettingViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience init(parentView : UIView) {
self.init(frame: parentView.frame)
let view : UIView = Bundle.main.loadNibNamed("BusinessSettingView", owner: self, options: nil)!.first as! UIView
view.frame = self.frame
view.alpha = 1
self.addSubview(view)
self.parentView = parentView
}
func showSetting() {
DispatchQueue.main.async {
self.parentView.addSubview(self)
}
}
//MARK: - button action
@IBAction func historyAction(_ sender: UIButton) {
if self.delegate != nil {
self.delegate?.businessSettingViewAction(settingView: self, button: sender)
}
}
}
// self.delegate is always nil