我有一个带有两个UIBarButtonItem的自定义UIToolbar类。我知道我可以为UIBarButtonItem项创建自定义委托操作。但是如何在自定义UIToolbar类初始化中使用闭包作为UIBarButtonItem操作?
class KeyboardToolBar: UIToolbar
{
let done = UIButton.init()
init() {
super.init(frame: .zero)
self.backgroundColor = UIColor.gray
self.sizeToFit()
let flexBarBtn = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
done.frame = CGRect(x: 0, y: 0, width: 50, height: 44)
done.setTitle("Done", for: .normal)
done.setTitleColor(.black, for: .normal)
let doneBarBtn:UIBarButtonItem! = UIBarButtonItem.init(customView: done)
self.items = [flexBarBtn,doneBarBtn]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
在ViewController中
super.viewDidLoad()
txt.keyboardType = .numberPad
txt.inputAccessoryView = KeyboardToolBar()
// How can I use some thing like this
// txt.inputAccessoryView = KeyboardToolBar(doneBtnAction: {
// print("done button pressed")
// })
}
答案 0 :(得分:2)
你去......
class KeyboardToolBar: UIToolbar {
let done = UIButton.init()
var doneBtnAction:((Void) -> Void)?
convenience init(_ doneBtnAction: @escaping (Void) -> Void) {
self.init()
self.doneBtnAction = doneBtnAction
}
private init() {
super.init(frame: .zero)
self.backgroundColor = UIColor.gray
self.sizeToFit()
let flexBarBtn = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
done.frame = CGRect(x: 0, y: 0, width: 50, height: 44)
done.setTitle("Done", for: .normal)
done.setTitleColor(.black, for: .normal)
done.addTarget(self, action: #selector(callbackDoneButton(_:)), for: .touchUpInside)
let doneBarBtn:UIBarButtonItem! = UIBarButtonItem.init(customView: done)
self.items = [flexBarBtn,doneBarBtn]
}
func callbackDoneButton(_ id:Any) -> Void {
if self.doneBtnAction != nil {
self.doneBtnAction!()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
在ViewController中
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
txt.keyboardType = .numberPad
txt.inputAccessoryView = KeyboardToolBar.init( {
(Void) -> Void in
print("done");
})
}