Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design a custom UIButton in a XIB file?

Tags:

ios

xib

uibutton

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?

like image 359
Samuel Noyes Avatar asked Oct 31 '22 00:10

Samuel Noyes


1 Answers

This is a little bit old.. Anyway, this is how I managed to do it on Xcode 10.1 and Swift 4.2.

  1. Create a .xib file, let's say CustomButton.xib and put a UIView contentView in it
  2. Create a .swift file, calling it the same, so CustomButton.swift
  3. Open the .swift file and define the custom class as follows:
import UIKit

class CustomButton: UIButton {

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

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

    enter image description here -----> enter image description here

    enter image description here -----> enter image description here

    (if you have "Inherit Module From Target" selected, leave the "Module" selection to Xcode)

  3. Now you should be able to ctrl-drag the contentView in its class file and have an outlet to reference it

  4. Create the initializers in your class, as follows.
@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.

like image 101
Martin Avatar answered Nov 12 '22 15:11

Martin