Swift: connect a static button with a static method - swift

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.

Related

All objects disappear in view controller (main storyboard) when I use custom #IBDesignable UITextfield class. (Xcode 10, Swift 4.2)

All objects disappear in view controller (main storyboard) when I use custom #IBDesignable UITextfield class. Main storyboard looks like this:
(Xcode 10, Swift 4.2)
As you see, it shows an error also. But Xcode shows 'Build Succeeded' when I run the app.
I use custom #IBDesignable UITextfield class like this below:
import UIKit
import AKMaskField
#IBDesignable
class MyTextFieldStyle: AKMaskField {
#IBInspectable var secureEntry : Bool = false
#IBInspectable var myBorderColor : UIColor = UIColor.white {
didSet {
self.layer.borderColor = myBorderColor.cgColor
}
}
#objc func secureButtonPressed (sender: UIButton) {
self.secureEntry = !self.secureEntry
self.isSecureTextEntry = self.secureEntry
}
override func awakeFromNib() {
super.awakeFromNib()
if self.secureEntry {
let btn = UIButton(type: .custom)
btn.setImage(#imageLiteral(resourceName: "eye-17-glyph-16"), for: .normal)
btn.addTarget(self, action: #selector(self.secureButtonPressed(sender:)), for: .touchUpInside)
btn.sizeToFit()
btn.frame = CGRect(x: self.frame.size.width-(btn.frame.size.width+5), y: (self.frame.size.height-btn.frame.size.height)/2, width: btn.frame.size.width, height: btn.frame.size.height)
self.addSubview(btn)
}
self.layer.borderColor = self.myBorderColor.cgColor
}
}
It becomes fine when I close and open Xcode. It looks like a bug. This was working fine.

Adding custom buttons to UITabBarController (adding button in the center)

i'm trying to make a custom tab bar with some images i made and i'm having some trouble. I'm trying to add a button to the tab bar and it seems like i can't do it. I want to do something like this:
Then adding some animations to that button. How can i go about adding that button? Do i need to subclass UITabBarController? Thank you!
In TabbarController class, add this code
override func viewDidLoad() {
super.viewDidLoad()
setupMiddleButton()
}
// MARK: - AddButton
func setupCenterButton() {
let centerButton = UIButton(frame: CGRect(x: 0, y: 10, width: 45, height: 45))
var centerButtonFrame = centerButton.frame
centerButtonFrame.origin.y = (view.bounds.height - centerButtonFrame.height) - 2
centerButtonFrame.origin.x = view.bounds.width/2 - centerButtonFrame.size.width/2
centerButton.frame = centerButtonFrame
centerButton.layer.cornerRadius = 35
view.addSubview(centerButton)
centerButton.setBackgroundImage(#imageLiteral(resourceName: "tabPost"), for: .normal)
centerButton.addTarget(self, action: #selector(centerButtonAction(sender:)), for: .touchUpInside)
view.layoutIfNeeded()
}
// MARK: - Center button Actions
#objc private func centerButtonAction(sender: UIButton) {
selectedIndex = 2
}
It will work.. :)
You should implement the delegate method of UITabBarControllerDelegate:
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if viewController == (self.tabBarController?.viewControllers?[theIndexOfTheButton])! {
// do my stuffs here
return false
}
return true
}
Don't forget to set self.tabBarController?.delegate = self

How to assign a custom class programmatically in swift for UIButton

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.

Swift dynamic button create

I am new in swift.
I have created dynamic button by pressing another button in the same viewController with following code:
#IBAction func yenibtn(sender: AnyObject) {
let btn = UIButton()
btn.frame = CGRectMake(10, 10, 50, 50) //set frame
btn.setTitle("btn", forState: .Normal) //set button title
btn.setTitleColor(UIColor.redColor(), forState: .Normal) //set button title color
btn.backgroundColor = UIColor.greenColor() //set button background color
btn.tag = 1 // set button tag
btn.addTarget(self, action: "btnclicked:", forControlEvents: .TouchUpInside) //add button action
self.view.addSubview(btn) //add button in view
}
func clickMe(sender:UIButton!)
{
print("Button Clicked")
}
and I created second viewController and navigate by performSegueWithIdentifier function. When i call back the previous controller the dynamic object disappears. Is there a way to retain dynamic button during reload of the previous ViewController?
Just use this:
var btn:UIButton!
#IBAction func yenibtn(sender: AnyObject) {
btn= UIButton()
btn.frame = CGRectMake(10, 10, 50, 50) //set frame
///... your code
}
UPDATE
Using your code in the second viewcontroller to close
#IBAction func basgeri(sender: AnyObject) {
performSegueWithIdentifier("bir", sender: self)
}
thinking "I'm closing the viewcontroller", BUT YOU ARE WRONG! You create a new ViewController! You are not returning to the previous one!
To fix it use this:
#IBAction func basgeri(sender: AnyObject) {
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}

swift Button display

I create a button from my code.
How can I write code to let button change to like Default?
Am I missing some code?
I have tried adjustsImageWhenHighlighted or something ....
I mean when I push Button ..the button will become to transparent(I still push on) and when i push off will become back ...
like down below two images...
import UIKit
class ViewController: UIViewController {
var testButton:UIButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.whiteColor()
testButton.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
testButton.backgroundColor = UIColor.whiteColor()
testButton.setTitle("123", forState:.Normal)
testButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
testButton.tag = 1
testButton.addTarget(self, action: #selector(number), forControlEvents: .TouchUpInside)
self.view.addSubview(testButton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func number(){
print("\("100")")
}
}
You could either add:
testButton.setTitleColor(UIColor.redColor(), forState: .Highlighted)
or have the colour applied in the button's function:
#IBAction func testButton(sender: UIButton) {
testButton.titleLabel.textColor = UIColor.redColor()
}
I've used redColor here for the examples, but you could change that to whatever colour you want to create the desired effect. I've not actually compiled this, so apologies if you need to correct any of the syntax to get it to work.