我正在开发原型阶段的应用程序.某些界面元素没有通过故事板或以编程方式分配给它们的任何操作.
根据UX准则,我想在应用程序中找到这些“非活动”按钮,并在测试期间点击时显示“功能不可用”警报.这可以通过扩展UIButton来完成吗?
除非通过界面生成器或以编程方式分配其他操作,否则如何为UIButton分配默认操作以显示警报?
解决方法
那么你想要实现的目标是什么.我已经使用UIViewController扩展并添加了一个闭包作为没有目标的按钮的目标.如果按钮没有动作,则会显示警报.
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)
}
}
我测试了它.希望这可以帮助.快乐的编码.