Hi Eskimo,
From GUI.swift, I am trying to create a generic button instantiator in one file (GUI.swift) that I can create in another file (ViewController.swift).
The issue is: "EXC_BAD_ACCESS (code=1, address= ... )" whenever I tap a button instantiated the way its done below:
File#1: GUI.swift
func BUTTON (_ view : UIView, tag : TAG, text : String, font : UIFont, textColor : UIColor, bgColor : UIColor, rect : CGRect, selector : Selector) {
let button = UIButton(type: UIButtonType.custom) as UIButton
button.tag = getTag(tag)
button.frame = rect
button.titleLabel?.textAlignment = NSTextAlignment.center
button.titleLabel!.font = font
button.setTitle(text, for: UIControlState())
button.setTitle(text, for: UIControlState.highlighted)
button.setTitleColor(textColor, for: UIControlState())
button.setTitleColor(textColor, for: UIControlState.highlighted)
button.addTarget(UIApplication.shared.windows , action: selector, for: UIControlEvents.touchDown)
button.backgroundColor = bgColor
view.addSubview(button)
}
func LABEL { ... }
func TEXTFIELD { ... }
...
File #2: ViewController.swift
...
//Create a button in ViewController.swift
BUTTON ( self.view, tag: 1, text: "text goes here", font: ..., textColor: ..., UIColor: ..., bgColor: ..., CGRect: ... , selector: #selector(ViewController.onClick(_:)) )
...
//onClick Function
func onClick (_ b : UIButton) {
switch b.tag {
case 1:
//Do Something when BUTTON with tag = 1 is pressed.
break
default: break
}
}
...
Hope this clears up some things.
This works in iOS10 but not in iOS 8.2 when written in Swift 3.0, however in Swift 2.0 (before migrating to 3.0) it worked for 8.2 perfectly.
Thanks again for taking the time to responding to my post!
Regards,
eigen