How to assign a custom class programmatically in swift for UIButton - swift

I have created a UIButton with system type
let systemButton = UIButton(type: .system)
I have a subclass of UIButton named SSRadioButton.
Instead of doing this thing in IB, I want to do it programmatically. All suggestions are welcome.

Instead of
let systemButton = UIButton(type: .system)
Use,
let systemButton = SSRadioButton()
and do further activity.

If your intention is to make it programmatically, simply implement:
// make sure to setup the frame as it should...
let myButton = SSRadioButton(frame: CGRect(x: 0, y: 0, width: 500, height: 50))
// OR, for your case:
//let myButton = SSRadioButton(type: .system)
myButton.addTarget(self, action: #selector(myButtonPressed), for: .touchUpInside)
// setup all pther needed properties...
view.addSubview(myButton)
Target of the button:
func myButtonPressed() {
print(#function)
}

You can have all details about UIButton () declaration in stack overflow: how to init a UIButton subclass?. It is a very complete answer and I do not have anything to add.

Related

Swift: connect a static button with a static method

Say I have a static button member variable, as well as a static method which handles its click. How can I connect the button with the method? I couldn't figure out how to get addTarget to work in this case:
private static let my_button: UIButton = {
let button = UIButton(type: .system)
...
button.addTarget(???, action: #selector(handleButtonClick), for: .touchUpInside)
return button
}()
private static func handleButtonClick() {
...
}
Could I put UIApplication.shared.keyWindow!.rootViewController in place of ????
Details
xCode 8.2.1, Swift 3
Full sample
import UIKit
class Button:NSObject {
class func createButton() -> UIButton {
let button = UIButton(type: .system)
button.frame = CGRect(x: 40, y: 40, width: 200, height: 40)
button.setTitle("Text", for: .normal)
button.addTarget(self, action: #selector(Button.handleButtonClick), for: .touchUpInside)
return button
}
class func handleButtonClick() {
print("Click")
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.addSubview(Button.createButton())
}
}
Result
You have to have an actual object - an instance of your class - as the button's target. It might be possible to pass the class object, but that's not how it's supposed to work. The button basically expects its target to be an object that inherits from NSResponder.

Custom UIButton as Navigation Item Back Button working, but does not show

let btnName = UIButton()
btnName.setImage(UIImage(named: "backIcon"), for: .normal)
btnName.addTarget(self, action: #selector(AddContactViewController.backAction), for: .touchUpInside)
let leftBarButton = UIBarButtonItem()
leftBarButton.customView = btnName
self.navigationItem.leftBarButtonItem = leftBarButton
It works fine, it does what is intended to do. However, on the navigation item it's invisible. But when I click on the area where it should be. It works.
Actually you may have two navigation bars one is of your current class and another is of your previous class.So, you can try by adding below code in your previous class.
override func viewWillDisappear(_ animated: Bool) {
self.navigationController!.navigationBar.isHidden = true
}
I also faced the same problem and it worked for me. May be it will help you.
Everything is ok, except you forgot to set the frame for your button, that's why it's not being shown.
let btnName = UIButton(frame: CGRect(x: 0, y: 0, width: 18, height: 17))
btnName.setImage(UIImage(named: "backIcon"), for: .normal)
btnName.addTarget(self, action: #selector(AddContactViewController.backAction), for: .touchUpInside)
let leftBarButton = UIBarButtonItem()
leftBarButton.customView = btnName
self.navigationItem.leftBarButtonItem = leftBarButton
Rather than hard-coding some frame values, you are better off calling the sizeToFit() method after setting the image, title, etc. I hit this problem today where a custom back button was showing OK on iOS11, but was not visible on iOS9.
btnName.sizeToFit()

Swift UIButton not appearing on screen

I have a view in my tabbar controller where I would like to show a button. I create this button programmatically based of a condition, therefore I use the following code but nothing is appearing:
override func viewDidLoad() {
super.viewDidLoad()
if !Settings.getIsConnected() {
notConnected()
}
}
func notConnected() {
let connectBtn = UIButton(frame: CGRect(x: self.view.center.x, y: self.view.center.y, width: 200, height: 45))
connectBtn.setTitle("Connect", forState: .Normal)
connectBtn.addTarget(self, action:#selector(self.pressedConnect(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(connectBtn)
print("Button created")
}
func pressedConnect(sender: UIButton!) {
}
I am clueless on what I am doing wrong. Anyone got suggestions? Cause it does print out "Button created" so it definitely runs the code inside the noConnected() method.
Add a background color to your UIButton and add a tint color to the title. This will resolve the problem
Try moving the code to viewDidAppear and see if the button is showing up.
The frame is not correctly set when in viewDidLoad. Use the method viewDidLayoutSubviews for the earliest possible time where the frame is correctly setup for a ViewController.
With this code change, you will need some additional logic for when your button should be added as a subview though.
A programmatically created button may not show up because of more reasons, e.g:
the tint color is not set
the background color is not set
the button is not added to the view hierarchy
the button is hidden
In your case, you should change the tint color or the background color of your button.
E.g.:
Swift 4.2:
private lazy var connectButton: UIButton = {
let button = UIButton(type: .custom)
button.backgroundColor = .green
button.setTitleColor(.black, for: .normal)
button.setTitle(NSLocalizedString("Connect", comment: ""), for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(connectButton)
}
You can re-check the button properties in the storyboard that it is not hidden.

Simple tvOS UIButton is not working

I'm trying to implement a simple UIButton (tvOS & Swift), but the TouchDown event isn't firing. (tried also TouchUpInside).
In the simulator I can see visually that the button is pressed.
my ViewController.swift code is:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: UIButtonType.System)
button.frame = CGRectMake(100, 100, 400, 150)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Test", forState: UIControlState.Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchDown)
self.view.addSubview(button)
self.view.userInteractionEnabled = true
}
func buttonAction(sender:UIButton!){
NSLog("Clicked")
}
}
What do I need to do in order to detect a button click?
You shouldn't be using ".TouchDown" or ".TouchUpInside" on tvOS, since that doesn't do what you might expect: you probably want to use "UIControlEvents.PrimaryActionTriggered" instead.
TouchUpInside is triggered by actual touches, which isn't really what happen. If you want the Select button press on the remote to trigger your button, you should use PrimaryActionTriggered.
UIControl.Event.primaryActionTriggered is required for tvOS addTarget method:
button.addTarget(self, action: #selector(ViewController.didTapAcctionButton(_:)), for: .primaryActionTriggered)

How to prevent side area clickable of UIBarButtonItem?

`
Whenever i click on this area , action also perform on this.
Don't worry about this behavior, iOS auto tapp near element if there is not other element.
If you really want to prevent to click except button, then you have to put Element on unused area which should be inherited from UIControl or able to get UserInteraction.
I got solution. I put one UIButton between these two UIBarButtonItem and make it custom and nil it's selector.
Also, you can try this: (Swift version)
let btnName = UIButton()
btnName.setImage(UIImage(named: "settings_filled_25"), forState: .Normal)
btnName.frame = CGRectMake(0, 0, 30, 30)
btnName.addTarget(self, action: Selector("toggleRight"), forControlEvents: .TouchUpInside)
var rightView = UIView()
rightView.frame = CGRectMake(0, 0, 30, 30)
rightView.addSubview(btnName)
let rightBarButton = UIBarButtonItem()
rightBarButton.customView = rightView
self.navigationItem.rightBarButtonItem = rightBarButton