gpt4 book ai didi

ios - 未触发自定义委托(delegate)方法

转载 作者:可可西里 更新时间:2023-11-01 00:55:19 26 4
gpt4 key购买 nike

我使用以下代码在 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()

}
}

看起来像这样。

enter image description here

现在每当我点击那个按钮时,HomeScreenVCViewController 中的方法就会被触发。所以我实现了这样的协议(protocol)和委托(delegate)。

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 方法没有被触发。任何帮助将不胜感激。

最佳答案

试试这段代码:

override func viewDidLoad() {
super.viewDidLoad()
(tabBarController.tabBar as? MainTabBar)?.buttonDelegate = self
}

关于ios - 未触发自定义委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50680942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com