【发布时间】:2017-03-21 20:11:53
【问题描述】:
我将 A 类中的选择器传递给 B 类中的方法,以最终触发 A 类中的委托方法 PressedButtonForMethodA。但是,我认为我的选择器有问题,因为委托方法或ClassB 的PressedButtonForMethodA()(ClassB.PressedButtonForMethodA() 仅用于调试目的)正在执行。使用 Swift 3 并且没有故事板。这是我在 swift 操场上的内容:
import UIKit
import PlaygroundSupport
class classA: UIViewController, ClassBDelegate {
private func setNavbarButtons() {
let myBarButton = classB()
myBarButton.delegate = self
let myBarButtonItem = myBarButton.setup("Press This", #selector(PressedButtonForMethodA))
self.navigationItem.rightBarButtonItem = myBarButtonItem
}
func PressedButtonForMethodA() {
NSLog("Method A in Class A fired!") // <<--THIS METHOD NOT BEING CALLED
}
}
protocol ClassBDelegate {
func PressedButtonForMethodA()
}
class classB: UIView {
var delegate: ClassBDelegate?
func setup(_ title: String, _ selectorAction: Selector) -> UIBarButtonItem {
let shadow = NSShadow()
shadow.shadowColor = UIColor.clear
let attributesNormal = [
NSForegroundColorAttributeName : UIColor.white,
NSShadowAttributeName : shadow,
NSFontAttributeName : UIFont.boldSystemFont(ofSize: 12.0)
]
let button = UIButton(type: .custom)
let buttonTitleAttributesNormal = NSAttributedString(string: title,
attributes: attributesNormal)
button.setAttributedTitle(buttonTitleAttributesNormal, for: UIControlState.normal)
let buttonTextSize = button.intrinsicContentSize
button.frame = CGRect(x: 0, y: 0, width: buttonTextSize.width, height: buttonTextSize.height)
button.addTarget(self, action: selectorAction, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)
return barButtonItem
}
func PressedButtonForMethodA() {
NSLog("Method A in Class B fired!") // <<-- THIS METHOD NOT FIRED EITHER
delegate?.PressedButtonForMethodA()
}
}
【问题讨论】:
-
如果你发布你的实际代码更容易帮助你 - 或者,至少有足够的代码可以使用和测试......
-
好点,DonMag。刚刚更新以包含我在 swift playground 中的实际代码。
标签: ios swift3 delegates protocols selector