Change the background of a view controller using a subclassed UIButton in a separate file

uibutton change background on touch
uibutton background color swift 4
uibutton change background color when pressed swift
uibutton background color for disabled state
uibutton transparent background swift
uibutton set background color objective-c
swift change background color programmatically
swift highlight button when pressed

I'm a beginner to Swift/iOS programming. I'm trying to do things programmatically. I created a subclass of a UIButton in a separate swift file. My objective is to just change the background of the underlying ViewController.

CustomButton.swift

import UIKit

class CustomButton: UIButton{
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.translatesAutoresizingMaskIntoConstraints = false
        self.backgroundColor = .blue
        self.setTitleColor(.white, for: .normal)
        self.setTitle("Press Me", for: .normal)
        self.layer.cornerRadius = 15
        // Button Action
        self.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

    }

    @objc func buttonPressed() {
        // Verify the method is called when the button is pressed
        self.setTitle("Pressed", for: .normal)
        // Change the background color for the ViewController
        let vc = ViewController()
        vc.view.backgroundColor = .red
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

ViewController.swift

import UIKit

class ViewController: UIViewController{

    let myButton = CustomButton()

    fileprivate func addElements() {
        view.addSubview(myButton)

        myButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 60).isActive = true
        myButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -60).isActive = true
        myButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 400).isActive = true
        myButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -400).isActive = true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        addElements()
    }


}

I'm not sure why this doesn't work or what I'm missing.

This doesn't work because you are creating a brand new VC here:

// Change the background color for the ViewController
let vc = ViewController() // This VC is not the same one as the one that's presented on screen
vc.view.backgroundColor = .red

Your custom UIButton do not and should not know about the view controller that controls it. The VC should handle this.

Your UIButton subclass should just be:

class CustomButton: UIButton{
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.translatesAutoresizingMaskIntoConstraints = false
        self.backgroundColor = .blue
        self.setTitleColor(.white, for: .normal)
        self.setTitle("Press Me", for: .normal)
        self.layer.cornerRadius = 15

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

You should add your VC as a target for the button, in the VC.

What I mean is:

// in viewDidLoad
let button = CustomButton(...)
button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)

// ...

func didTapButton() {
    view.backgroundColor = .red
}

How to change the background color of a UIButton while it's , If I have a button in a view controller named ConversionViewController, how You can use property observer to trigger background color change: extension UIButton { private func imageWithColor(color: UIColor) -> UIImage { let rect Similar to subclassing, without requiring a subclass. Cancel and add another image. I have a Collections View that includes various cells that are also buttons. Upon clicking one of those buttons, a separate ViewController is shown (I just connected the button to the ViewController and clicked "show"). I would like to know how to switch the textView in that separate ViewController for every different button in my Collections View.

If you want to change the background color of UIViewController then you have to pass that controller.

Follow these steps:-

1st step - Create a custom button class and create a viewController variable type of UIViewController so you can assign the specific controller to change the background of UIViewController color.

import UIKit

class CustomButton: UIButton {

    var viewController: UIViewController?

    override func awakeFromNib() {
        super.awakeFromNib()

        self.addTarget(self, action: #selector(buttonPressed(sender:)), for: .touchUpInside)
    }

    @objc func buttonPressed(sender: UIButton) {
        viewController?.view.backgroundColor = UIColor.red
    }

}

2nd step - UIViewController code

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var button: CustomButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        button.viewController = self //Assigning controller using self keyword

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)

    }

}

Building iOS Interfaces: Subclassing Views, Name your class RoundedCornerButton then set UIButton in the Subclass of field​. In the new Swift file, go ahead and delete all the comments – lines starting with // – the need direct access to our button instance in the view controller. object in IB and manually change the background color attribute. In order to ensure that your code is working as intended, you can change the background of the View Controller by heading to the respective LoginScreenViewController.swift file (the name of your

Foundation iPhone App Development: Build An iPhone App in 5 Days , There's a problem, however: we want buttons in the same container class to have different styles. Apple's Name your class BRBlueButton and subclass UIButton. For each of the buttons in the Birthday Detail view controller scene back in Using the identity inspector, change the custom class of the first four buttons to  Change the background of a view controller using a subclassed UIButton in a separate file Hot Network Questions Why is the autopilot of the DHC-6 Twin Otter powered by bleed air?

iOS 13 Programming Fundamentals with Swift: Swift, Xcode, and , You wouldn't subclass UITextField just in order to respond in some special way when Every Cocoa app uses view controllers, but a plain vanilla UIViewController, not UIView subclasses that behave and draw themselves as needed (UIButton, In MyHorizLine.swift, replace the contents of the class declaration with this  Storyboards also incorporate transitions between those view controllers. A XIB represents the UI information of one view or view controller class, whereas a storyboard represents many view controllers. You can use XIBs for views and view controllers. The XIB itself just contains information about views and their attributes.

Programming IOS 8: Dive Deep Into Views, View Controllers, and , Dive Deep Into Views, View Controllers, and Frameworks Matt Neuburg. Another conflict that can arise is between a gesture recognizer and a view to recognize taps on the background), but there is also a UIButton within it. It is called automatically; to modify its behavior, use a custom UIView subclass and over‐​ride it. Your code is just fine. The reason you’re getting a black screen is because there’s nothing on your second view controller. Try something like: secondViewController.view.backgroundColor = UIColor.redColor(); Now the view controller it shows should be red.

Programming IOS 9: Dive Deep Into Views, View Controllers, and , Dive Deep Into Views, View Controllers, and Frameworks Matt Neuburg to be able to recognize taps on the background), but there is also a UIButton within it. It is called automatically; to modify its behavior, use a custom UIView subclass and Another way of resolving possible gesture recognizer conflicts is through the  Although you could achieve the same using UIButton. Create an UIButton object then set an action method and add your picker view in parent view of your button in the action method of UIButton. Should be something like that.-(void) buttonClicked:(id) sender { [self.view addSubview:myPickerView]; }

Comments
  • Based on your code CustomButton would need a reference to the parent view. You could use the button's superview property, but personally, I'd add a target in ViewController to respond to the button and let the ViewController take care of it
  • Ah I see...Putting the addTarget... and the associated function in the ViewController file worked. Thank You.
  • @Yetimate If you think my answer answers your question, please consider accepting it by clicking on that checkmark!
  • This is not the good way to do, don't give customButton a reference to it parentController. CustomButton inherit from UIButton so you can addTarget(_) directly from the view controller :)
  • He wants to change the color of a controller so Custombutton property code should be in CustomButton own file. if he wants to implement not related to that particular class then is it ok to do in the button action method in ViewController file. The more you code split into write file the more you can understand