In my custom view I’ve created one button. To add action for that button which is feasible solution Creating Delegate method or Declaring UIButton
as global variable and addTaget
. Suggest me please.
Asked
Active
Viewed 251 times
0

Karthikeyan Bose
- 1,244
- 3
- 17
- 26
-
Some context would probably be helpful... – Couchy Apr 27 '17 at 05:05
-
4If you want to perform action within the custom view then you can use addTarget. If you want to perform action where you'll add the view then you should use custom delegate. – RajeshKumar R Apr 27 '17 at 05:06
-
what you want to do ? – KKRocks Apr 27 '17 at 05:07
-
Better use addTarget. [buttonName addTarget:self action:@selector(clickedButton:) forControlEvents:UIControlEventTouchUpInside] – QUserS Apr 27 '17 at 05:09
-
@RajeshkumarR: i'l perform only where I creating a view. – Karthikeyan Bose Apr 27 '17 at 05:16
-
@QUserS: As for now am using that method only. Just I want to know is I'm correct or not. – Karthikeyan Bose Apr 27 '17 at 05:17
-
do you want to call this method in view class or any where in app ? – KKRocks Apr 27 '17 at 05:39
-
definitely not in inside the view @KKRocks – Karthikeyan Bose Apr 27 '17 at 05:42
-
then what is the problem faced here ? – KKRocks Apr 27 '17 at 05:43
-
I didn't faced any problem. I need to know which one is feasible solution for `UIButton` action. @KKRocks – Karthikeyan Bose Apr 27 '17 at 05:46
-
1if you want to call this method inside in the class only then UIButton selector method is perfect . – KKRocks Apr 27 '17 at 05:47
-
Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/142785/discussion-between-karthikeyan-bose-and-kkrocks). – Karthikeyan Bose Apr 27 '17 at 05:49
2 Answers
1
I'd highly recommend not using global vars as much as possible. Global data (constants) are good, but global variables are high maintenance since anyone can modify it.
There are 2 cases why you may want a global variable:
- It has to trigger different actions in multiple unrelated submodules. What I'd recommend here is to create the button and target in a class/function, and send a notification in the target. Make the different subsystems register to the notification and take appropriate action
- You just have one class to take an action item, but it's convenient to not have delegates and use global vars. I request you to prefer design to convenience.

7to4
- 198
- 1
- 8
1
Please don't use global variables. You have two option for same:
- If you are using custom class then you have to use delegate methods
- Another option is that: You can create a method with UIButton return type and use this method to create action method on the button in any class.
Note: I'd highly recommend you that you have to use delegate methods.

Jogendar Choudhary
- 3,476
- 1
- 12
- 26