Reputation: 13
How to create an action for the button in the custom view created from nib.
I created an Outlet
, it got hooked up to the custom ViewController
, but when I try to have an action, it doesn't work.
Upvotes: 1
Views: 1625
Reputation: 395
//Button action using both addTarget and Closure
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: CustomImageView!
@IBOutlet weak var awesomeView: AwesomeView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
awesomeView.button1.addTarget(self, action: #selector(button1Action(_:)), for: .touchUpInside)
awesomeView.button2Pressed = {
print("Closure button pressed")
}
}
@objc func button1Action(_ sender: UIButton) {
// do something here
}
}
//UIView Declaration
@IBDesignable class AwesomeView: UIView {
let kCONTENT_XIB_NAME = "AwesomeView"
@IBOutlet var containerView: UIView!
@IBOutlet weak var button1 : UIButton!
@IBOutlet weak var button2 :UIButton!
//create your closure here
var button2Pressed : (() -> ()) = {}
override init(frame: CGRect) {
super.init(frame: frame)
initNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initNib()
}
func initNib() {
let bundle = Bundle(for: AwesomeView.self)
bundle.loadNibNamed(kCONTENT_XIB_NAME, owner: self, options: nil)
addSubview(containerView)
containerView.frame = bounds
containerView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
@IBInspectable var button1Title: String = "" {
didSet {
button1.setTitle(button1Title, for: .normal)
}
}
@IBAction func tapOnButtonPressed(_ sender: Any) {
}
@IBAction func tapOnButton2Pressed(_ sender: Any) {
button2Pressed()
}
}
Upvotes: 0
Reputation: 3325
yourView.yourButton.addTarget(self, action: #selector(yourFuncName(_:)), for: .touchUpInside)
then somewhere declare your func as below :
@objc func yourFuncName(_ sender: UIButton) {
do something here}
Upvotes: 0
Reputation: 207
If you are working with a nib or storyboard file, then you don't even need the outlet to the button. Simply drag from the button to your class and select "Action" instead of "Outlet". It even lets you select which type of Actions you want to receive, such as "TouchUpInside". If you need to do changes to the button, after it has been clicked, you can also do that inside the newly generated method, as it has a sender property, which is your button.
Upvotes: 1
Reputation: 5967
This is what you can do
Create an outlet of your VIEW (the custom view) instead. Then add selector to the button like this
self.viewName.buttonName addTarget:self action:@selector(actionName) forControlEvents:UIControlEventTouchUpInside];
There are other options like passing a block to the view OR using Delegate pattern, but those will be more of a overkill to do such a simple task. This would be way simplier and better when you are working on a separate view in an XIB
Upvotes: 2