iOS Swift - 如何以编程方式为所有按钮指定默认操作
我正在开发原型阶段的应用程序。某些界面元素没有通过故事板或编程方式分配给它们的任何操作。
I'm working with an app in prototype stage of development. Some interface elements do not have any action assigned to them either through storyboard or programmatically.
根据UX准则,我想在应用程序中找到这些非活动按钮,并在测试期间点击时显示功能不可用警报。这可以通过UIButton的扩展来完成吗?
According to UX guidelines, I want to find these "inactive" buttons in app and have them display a "feature not available" alert when tapped during testing. Can this be done through an extension of UIButton?
除非通过界面构建器分配了另一个操作,否则如何为UIButton分配默认操作以显示警报以编程方式?
那么你想要实现的目标是什么。我使用 UIViewController
扩展并添加了一个闭包作为没有目标的按钮的目标。如果按钮没有动作,则会显示警报。
Well what you are trying to achieve can be done. I have done this using a UIViewController
extension and adding a closure as the target of a button which does not have a target. In case the button does not have an action an alert is presented.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.checkButtonAction()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func btn_Action(_ sender: UIButton) {
}
}
extension UIViewController{
func checkButtonAction(){
for view in self.view.subviews as [UIView] {
if let btn = view as? UIButton {
if (btn.allTargets.isEmpty){
btn.add(for: .touchUpInside, {
let alert = UIAlertController(title: "Test 3", message:"No selector", preferredStyle: UIAlertControllerStyle.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
})
}
}
}
}
}
class ClosureSleeve {
let closure: ()->()
init (_ closure: @escaping ()->()) {
self.closure = closure
}
@objc func invoke () {
closure()
}
}
extension UIControl {
func add (for controlEvents: UIControlEvents, _ closure: @escaping ()->()) {
let sleeve = ClosureSleeve(closure)
addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
objc_setAssociatedObject(self, String(format: "[%d]", arc4random()), sleeve, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
我已经测试过了。希望这可以帮助。快乐的编码。
I have tested it. Hope this helps. Happy coding.