I'm trying to create a custom UIButton for a Radio Button class. When selected, the button should have a background color of orange with a text color of white, and when unselected it should have a background color of white with a text color of black. I was able to do this programmatically by adding a colored UIView below the button's text label, but I was hoping to do this with a XIB file. However, I can't for the life of me find an online tutorial for designing a UIButton in a XIB file. Is there a way to do this? Could anyone tell me how or point me to a tutorial?
Edit: For clarity, I am using storyboards. I'm not talking about a xib file for the entire view controller. I'm talking about making a XIB file ONLY for the one button. Is this possible?
This is a little bit old.. Anyway, this is how I managed to do it on Xcode 10.1 and Swift 4.2.
CustomButton.xib
and put a UIView contentView
in itCustomButton.swift
import UIKit class CustomButton: UIButton { }
Now open the .xib and select contentView
, then Size -> Freeform in the Attributes Inspector. In this way you can manipulate the contentView
size in IB
IMPORTANT. In the Identity Inspector, do not assign the custom class to contentView
, i.e., the main view of the .xib. Assign it to the File's Owner instead
----->
----->
(if you have "Inherit Module From Target" selected, leave the "Module" selection to Xcode)
Now you should be able to ctrl-drag the contentView
in its class file and have an outlet to reference it
@IBOutlet weak var contentView: UIView! // init used if the view is created programmatically override init(frame: CGRect) { super.init(frame: frame) self.customInit() } // init used if the view is created through IB required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.customInit() } // Do custom initialization here private func customInit() { Bundle.main.loadNibNamed("CustomButton", owner: self, options: nil) self.addSubview(self.contentView) self.contentView.frame = self.bounds self.contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth] }
Now you should be able to design your CustomButton with .xib and use it wherever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With