我使用以下代码在TabBarController中添加了一个圆形按钮
import UIKit
protocol AddButtonProtocol: class {
func addButtonIsClicked()
}
class MainTabBar: UITabBar {
open var buttonDelegate: AddButtonProtocol?
private var middleButton = UIButton()
override open func awakeFromNib() {
super.awakeFromNib()
setupMiddleButton()
}
override open func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if self.isHidden {
return super.hitTest(point, with: event)
}
let from = point
let to = middleButton.center
return sqrt((from.x - to.x) * (from.x - to.x) + (from.y - to.y) * (from.y - to.y)) <= 39 ? middleButton : super.hitTest(point, with: event)
}
func setupMiddleButton() {
middleButton.frame.size = CGSize(width: 70, height: 70)
middleButton.backgroundColor = .blue
middleButton.layer.cornerRadius = 35
middleButton.layer.masksToBounds = true
middleButton.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 0)
middleButton.addTarget(self, action: #selector(test), for: .touchUpInside)
addSubview(middleButton)
}
@objc func test() {
print("add button is clicked")
buttonDelegate?.addButtonIsClicked()
}
}
看起来像这样。
现在每当我点击该按钮时,都应该触发HomeScreenVCViewController
中的方法。所以我已经实现了这样的协议和代理。
import UIKit
class HomeScreenVCViewController: UIViewController {
var addButtonDelegate: MainTabBar!
override func viewDidLoad() {
super.viewDidLoad()
addButtonDelegate?.buttonDelegate = self
}
}
extension HomeScreenVCViewController: AddButtonProtocol {
func addButtonIsClicked() {
print("protocol is working") // Not getting called
}
}
但它根本不起作用,当我点击那个圆形按钮时,addButtonIsClicked方法没有被触发。任何帮助将不胜感激。
答案 0 :(得分:1)
代表没有被称为b'coz addButtonDelegate
是零。您没有初始化addButtonDelegate
,因此addButtonDelegate
对象为nil
<强>解决方案强>
您需要将addButtonDelegate
设为@IBOutlet
,或者需要在viewDidLoad:
方法中对其进行初始化。
然后只会调用委托。
示例1
@IBOutlet weak var addButtonDelegate: MainTabBar!
并在viewDidLoad
中addButtonDelegate.buttonDelegate = self
示例2
创建像
这样的属性var addButtonDelegate: MainTabBar?
在viewDidLoad初始化addButtonDelegate
。
addButtonDelegate = MainTabBar() //or any other initialiser
addButtonDelegate?.buttonDelegate = self
答案 1 :(得分:1)
您未在MainTabBar
中初始化HomeScreenVCViewController
。这就是为什么addButtonDelegate
是nil
var addButtonDelegate: MainTabBar = MainTabBar()
override func viewDidLoad() {
super.viewDidLoad()
addButtonDelegate?.buttonDelegate = self
}
答案 2 :(得分:1)
试试这段代码:
override func viewDidLoad() {
super.viewDidLoad()
(tabBarController.tabBar as? MainTabBar)?.buttonDelegate = self
}