[ios] Change button background color using swift language

I am new to the swift language. Can someone tell me how to change the background color of a button using the swift language?

This question is related to ios iphone colors uibutton swift

The answer is


Swift 3

Color With RGB

btnLogin.backgroundColor = UIColor.init(colorLiteralRed: (100/255), green: (150/255), blue: (200/255), alpha: 1)

Using Native color

btnLogin.backgroundColor = UIColor.darkGray

After you connect the UIButton that you want to change its background as an OUtlet to your ViewController.swift file you can use the following:

 yourUIButton.backgroundColor = UIColor.blue

If you want to set backgroundColor of button programmatically then this code will surly help you

Swift 3 and Swift 4

self.yourButton.backgroundColor = UIColor.red

Swift 2.3 or lower

self.yourButton.backgroundColor = UIColor.redColor()

Using RGB

self.yourButton.backgroundColor = UIColor(red: 102/255, green: 250/255, blue: 51/255, alpha: 0.5)

or you can use float values

button.backgroundColor = UIColor(red: 0.4, green: 1.0, blue: 0.2, alpha: 0.5)

U can also play around the tintcolor and button image to indirectly change the color.


button.backgroundColor = UIColor.blue

Or any other color: red, green, yellow ,etc.

Another option is RGBA color:

button.backgroundColor = UIColor(red: 0.4, green: 1.0, blue: 0.2, alpha: 0.5)

/*Swift-5 update*/

let tempBtn: UIButton = UIButton(frame: CGRect(x: 5, y: 20, width: 40, height: 40))       
tempBtn.backgroundColor = UIColor.red

Try this, you need to add the 255 like so:

button.backgroundColor = UIColor(red: 102/255, green: 250/255, blue: 51/255, alpha: 0.5)

Update for xcode 8 and swift 3, specify common colors like:

button.backgroundColor = UIColor.blue

the Color() has been removed.


To change your background color of the botton use:

yourBtn.backgroundColor = UIColor.black

if you are using storyBoard make sure you have connected your storyBoard with your viewController and also that your items are linked.

if you don´t know how to do this check the next link:

How to connect ViewController.swift to ViewController in Storyboard?


Swift 4:

You can easily use hex code:

self.backgroundColor = UIColor(hexString: "#ff259F6C")

self.layer.shadowColor = UIColor(hexString: "#08259F6C").cgColor

Extension for hex color code

extension UIColor {
    convenience init(hexString: String, alpha: CGFloat = 1.0) {
        let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)
        if (hexString.hasPrefix("#")) {
            scanner.scanLocation = 1
        }
        var color: UInt32 = 0
        scanner.scanHexInt32(&color)
        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        self.init(red:red, green:green, blue:blue, alpha:alpha)
    }
    func toHexString() -> String {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: &a)
        let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
        return String(format:"#%06x", rgb)
    }
}

You can set the background color of a button using the getRed function.
Let's assume you have:

  1. A UIButton called button, and
  2. You want to change button's background color to some known RBG value

Then, place the following code in the function where you want to change the background color of your UIButton

var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0

// This will be some red-ish color
let color = UIColor(red: 200.0/255.0, green: 16.0/255.0, blue: 46.0/255.0, alpha: 1.0) 

if color.getRed(&r, green: &g, blue: &b, alpha: &a){
    button.backgroundColor = UIColor(red: r, green: g, blue: b, alpha: a)
}

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to colors

is it possible to add colors to python output? How do I use hexadecimal color strings in Flutter? How do I change the font color in an html table? How do I print colored output with Python 3? Change bar plot colour in geom_bar with ggplot2 in r How can I color a UIImage in Swift? How to change text color and console color in code::blocks? Android lollipop change navigation bar color How to change status bar color to match app in Lollipop? [Android] How to change color of the back arrow in the new material theme?

Examples related to uibutton

How to make a simple rounded button in Storyboard? How to set the title text color of UIButton? How can I make a button have a rounded border in Swift? How to change UIButton image in Swift Changing text of UIButton programmatically swift Disable a Button How to change font of UIButton with Swift Attach parameter to button.addTarget action in Swift Change button background color using swift language Make a UIButton programmatically in Swift

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?