Reputation: 685
I have added a round button in TabBarController using the following code
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()
}
}
It looks like this.
Now whenever I click that button, the method in HomeScreenVCViewController
should be triggered. So I have implemented the protocol and delegates like this.
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
}
}
But its not working at all, addButtonIsClicked method is not getting triggered when I tap that round button. Any help will be appreciated.
Upvotes: 2
Views: 302
Reputation: 286
Try this code:
override func viewDidLoad() {
super.viewDidLoad()
(tabBarController.tabBar as? MainTabBar)?.buttonDelegate = self
}
Upvotes: 1
Reputation: 3682
You did not initialize MainTabBar
in HomeScreenVCViewController
. Thats why addButtonDelegate
is nil
var addButtonDelegate: MainTabBar = MainTabBar()
override func viewDidLoad() {
super.viewDidLoad()
addButtonDelegate?.buttonDelegate = self
}
Upvotes: 1
Reputation: 8924
Delegate is not getting called b'coz addButtonDelegate
is nil. You do not initialise addButtonDelegate
so the addButtonDelegate
object is nil
Solution
Either you need to make addButtonDelegate
as an @IBOutlet
or you need to initialise it in viewDidLoad:
method.
Then only delegate will be called.
Example 1
@IBOutlet weak var addButtonDelegate: MainTabBar!
and in viewDidLoad
addButtonDelegate.buttonDelegate = self
Example 2
Create property like
var addButtonDelegate: MainTabBar?
in viewDidLoad initialise addButtonDelegate
.
addButtonDelegate = MainTabBar() //or any other initialiser
addButtonDelegate?.buttonDelegate = self
Upvotes: 1