swift Button display - swift

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.

Related

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

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.

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 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.

UIButton in UIScrollView->UIStackView->UIView not clicking

I am having trouble figuring out why a UIButton will not click. I have a UIScrollView that contains a UIStackView where I am programmatically placing subviews. I am creating the subviews and placing them into the stack view with the following:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var stackView: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let vc0 = self.storyboard?.instantiateViewControllerWithIdentifier("vc0") as UIViewController!
let vc1 = self.storyboard?.instantiateViewControllerWithIdentifier("vc1") as UIViewController!
self.stackView.addArrangedSubview(vc0.view)
self.stackView.addArrangedSubview(vc1.view)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// mulitply by two in order to scale it to the size of each `addArrangedSubview`, subtract the height of the embedded navbar
scrollView.contentSize = CGSize(width: stackView.frame.width * 2, height: stackView.frame.height - 64)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The only other changes I have made are with the constraints:
I should note that vc0 and vc1 are simple UIViews with a UIButton set to show another simple UIView.
Any help would be much appreciated!
EDIT:
I have added a button to vc0 programmatically and the click is working. Why would this button work and one from storyboard not work?
...
let vc0 = self.storyboard?.instantiateViewControllerWithIdentifier("vc0") as UIViewController!
...
let btn=UIButton(type: .System)
btn.frame = CGRectMake(100, 100, 32, 32)
btn.addTarget(self, action: "pressed", forControlEvents: .TouchUpInside)
btn.setTitle("Press Me", forState: .Normal)
vc0.view.addSubview(btw)
...