Is there a different option than addTarget on a UIButton - ios

addTarget
So I know that you can use addTarget on a button
like so:
import UIKit
class ViewController: UIViewController {
func calledMethod(_ sender: UIButton!) {
print("Clicked")
}
override func viewDidLoad() {
super.viewDidLoad()
let btn = UIButton(frame: CGRect(x: 30, y: 30, width: 60, height: 30))
btn.backgroundColor = UIColor.darkGray
btn.addTarget(self, action: #selector(self.calledMethod(_:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(btn)
}
}
This works absolutely fine but I was just wondering is there another way to detect when something is clicked and run some code when that happens.

You can add button in the storyboard and create an outlet for it's action.
#IBAction func buttonAction(_ sender: UIButton) {
//implement your code here
}

A button is a subclass of UIControl. A UIControl is designed to use target/action to specify code to run when the specified action occurs. If you don't want to use that mechanism, you have to create an equivalent.
You could attach a tap gesture recognizer to some other object and set it's userInteractionEnabled flag to true, but gesture recognizers ALSO use the target/action pattern.
My suggestion is to "stop worrying and learn to love the button." Just learn to use target/action.
Another possibility: Create a custom subclass of UIButton that sets itself up as it's own target at init time (specifically in init(coder:) and init(frame:), the 2 init methods you need to implement for view objects.) This button would include an array of closures that its action method would execute if the button was tapped. It would have methods to add or remove closures. You'd then put such a button in your view controller and call the method to add the closure you want.

You can also have a look at RxSwift/RxCocoa or similar. All the changes and actions are added automatically and you can decide if you want to observe them or not.
The code would look something like this:
let btn = UIButton(frame: CGRect(x: 30, y: 30, width: 60, height: 30))
btn.backgroundColor = UIColor.darkGray
btn
.rx
.tap
.subscribe(onNext: {
print("Clicked")
}).disposed(by: disposeBag)
view.addSubview(btn)

Related

How do we prevent calling the method programmatically?

We need to prevent a method call programmatically. We just want to call method with user interaction from UI.
Actually, We're developing a SDK. We have some custom UI object classes. We want to avoid the user access to target methods without using our custom UI objects.
UIButton is just an example. It can be UISwitch or another UI element. Or maybe SwiftUI elements.
This is required as a security measure. It is a precaution we want to put so that malicious people do not call it as if it is an operation from the interface.
We want the operation to be performed only from the interface. So we check the information in Thread.callStackSymbols. But this code doesn't work in Testflight or release. It only works in debug mode.
You will see a UIButton below example. When clicked it’ll call clickedButton. But there is a method that call maliciousMethod. It can call clickedButton programmatically. We want to prevent it.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
button.backgroundColor = .red
button.setTitle("Click Me", for: .normal)
self.view.addSubview(button)
button.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
}
#objc func buttonClicked(_ sender : UIButton) {
/// We need to check action called from UI or another method here.
let symbols = Thread.callStackSymbols
let str: String = symbols[3]
if str.contains("sendAction") == false && str.contains("SwiftUI7Binding") == false {
print("It's called from programmatically. Abort")
return
}
}
/// We want to prevent this kind of call
func maliciousMethod() {
buttonClicked(UIButton())
}
}
There's not much you can do if someone has access to your code base, so I assume your ViewController is part of a binary framework to be distributed, that you want to secure against malicious programmers. In that case, you could store the button you want to allow as a private or fileprivate property in your ViewController. Then check for it in buttonClicked().
So something like this:
class ViewController: UIViewController {
fileprivate var secureButton: UIButton! // <-- Added this
override func viewDidLoad() {
super.viewDidLoad()
// Using/saving the secureButton here
secureButton = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
...
}
#objc func buttonClicked(_ sender : UIButton) {
/*
Check for the expected sender here. You probably don't want to
actually fatalError, but rather do something more sensible for
you app/framework
*/
guard sender === secureButton else {
fatalError("Strange things are afoot at the Circle-K")
}
...
}
/// This method will now trigger the guard in buttonClicked
func maliciousMethod() {
buttonClicked(UIButton())
}
}

UIButton with multiple target actions for same event

Can I add multiple target actions on a UIButton for the same event like below?
[button addTarget:self action:#selector(xxx) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:object action:#selector(yyy) forControlEvents:UIControlEventTouchUpInside];
I made a quick app to test it out and it carries out both the actions on button press.
I want to know if it's good practice to do so, and also will the order of execution always remain the same?
Thanks in advance.
Edit: I did find this post which states it's called in reverse order of addition, i.e., the most recently added target is called first. But it's not confirmed
Yes it is possible to add multiple actions to a button.
personally i would prefer a Delegate to subscribe to the button.
Let the object you want to add as target subscribe on the delegate's method so it can receive events when you press the button.
or
A single action that forwards the event to other methods to be fully in control
A simple test in swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let button = UIButton(frame: CGRect(x: 50, y: 50, width: 300, height: 30))
button.backgroundColor = .orange
button.addTarget(self, action: #selector(action1), for: .touchUpInside)
button.addTarget(self, action: #selector(action2), for: .touchUpInside)
button.addTarget(self, action: #selector(actionHandler), for: .touchUpInside)
self.view.addSubview(button)
}
#objc func actionHandler(_ sender: UIButton){
print("actionHandler")
action1(sender)
action2(sender)
}
#objc func action1(_ sender: UIButton) {
print("action1")
}
#objc func action2(_ sender: UIButton) {
print("action2 \n")
}
}
Output after one click:
action1
action2
actionHandler
action1
action2
Can you confirm on the order of execution when normally adding the actions
Yes it is executed in the order you set the targets.

Get sender's tag of a programmatically set button ios

I wish to get the sender's tag of a programmatically set button.
i have set many buttons with tags programmatically and when the app is running and one of the buttons is tapped i wish to get the sender's tag back.
An example in my project. This #IBAction is connected with 7 buttons, from Monday to Sunday.
#IBAction func OnBtnWeekDay(_ sender: UIButton) {
let day = sender.tag - 1
//....
}
Main point is the parameter of function: (_ sender: UIBUtton)
This is simple. Make a button programmatically e.g in viewdidload and set it's tag and add action to it using the following code
//make a button programmatically e.g in viewdidload
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
//set tag to any integer value
button.tag = 1
//add to view controllers view or where ever you want
self.view.addSubview(button)
#objc func buttonAction(sender: UIButton!) {
print("Button tapped")
print("Buttons Tag is \(sender.tag)")
}
Tested and verified this solution my self. see the screen shot

Access UIControls from Views outside the storyboard

My view (in the Main.storyboard) contains another UIView which takes only about 80% of the screen's height (set with constraints).
In this second view (I call it the viewContainer) I want to display different views, which works with
viewContainer.bringSubview(toFront: someView)
I created a new group in my project which contains 3 UIViewController classes and 3 xib files which I want to display in my viewContainer.
For each of those xib files I changed the background color to something unique so I can tell if it's working. And it does so far.
Now I tried adding a UIButton to the first UIViewController class and added an #IBAction for it. That just prints text to the console.
When I run the app I can switch between my 3 classes (3 different background colors) and I can also see and click the button I added to the first class when I select it.
But the code is never executed and my console is empty. Is that because my 3 other Views are not shown in my Main.storyboard?
SimpleVC1.swift
import UIKit
class SimpleVC1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func onButtonPressed(_ sender: Any) {
print("test")
}
}
Try using a target instead (and programmatically create the button), it might be easier:
import UIKit
class SimpleVC1: UIViewController {
var button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(button)
button.frame.size = CGSize(width: 100, height: 100)
button.center = CGPoint(x: 100, y: 100)
button.setTitle("Control 1", for: .normal)
button.addTarget(self, action: #selector(control1), for: .touchUpInside)
button.backgroundColor = UIColor.blue
button.setTitleColor(UIColor.white, for: .normal)
}
#objc func control1() {
//Add your code for when the button is pressed here
button.backgroundColor = UIColor.red
}
}

Swift - UIButton created programatically doesn't trigger touch event

I have created a button programatically and want to add a touch event handler. I have tried all the tricks I have found online but the desired function is just never triggered.
upgradeNowView = UIButton()
upgradeNowView.setTitle("Upgrade", forState: .Normal)
upgradeNowView.contentMode = UIViewContentMode.ScaleToFill
upgradeNowView.frame = CGRect(x: upgradeNowView.frame.minX, y: -50 , width: 320, height: 50)
upgradeNowView.userInteractionEnabled = true
upgradeNowView.sendActionsForControlEvents(.TouchUpInside)
upgradeNowView.addTarget(self, action: #selector(MainViewContainer.upgradeTapped(_:)), forControlEvents: .TouchUpInside)
side_menu_controller?.view.addSubview(upgradeNowView)
and defined this
func upgradeTapped(sender: UIButton)
{
UpgradeViewController.openUpgrade()
}
But this just never gets called. Any help would be appreciated.
You need to define upgradeTapped function in class of side_menu_controller instance. I guess, it's SideMenuController class.
I found out this was caused by the fact that I was placing the button next to the view but outside its bounds (just on top):
upgradeNowView.frame = CGRect(x: upgradeNowView.frame.minX, y: -50 , width: 320, height: 50)
There are two ways around this:
Move the button inside the bounds of the parent view, or
Handle touches outside the view by overriding "hitTest" as discussed here

Resources