Right now I’m kind of teaching myself Swift and iOS programming because:

  • Swift is a badass language
  • iOS coding is fun and different than the web
  • It’s fun!

One of the issues I had the other day was finding a simple, easy way to programatically resize a XIB file (specifically for a custom keyboard I am working on). I searched high and low on stackoverflow and Google, but to no avail. I kept thinking “OKAY someone has to know how to do this or has done this.”

So I found this simple example using UITextField and tried to apply it to my XIB view. AND IT WORKED GREAT.

So I’ll guide you through how to do this in Swift. This tutorial requires a basic understanding of XCode and the Storyboard features.

PREREQUISITE KNOWLEDGE

  • Swift syntax/semantics
  • Storyboard
  • ViewController
  • ViewController Button binding

STEP ONE: Hooking up the ViewController with it’s XIB

You’ll want to create a regular old “View” in XCode. Once that is done, choose Add File from the File menu.

Then you’ll want to click on your XIB in the Storyboard editor and click on the “File’s Owner” object/cube. Finally, go over to the File Owner’s Identity Inspector and change it’s class to YourViewController (whatever you named it). Cool!

In your ViewController we want to make sure we have a reference to our XIB. So we’ll want to add something like this:

    var myXibView: UIView!

Our XIB is connected to our ViewController file. Let’s move on.

STEP TWO: Changing Attributes of the View.

Once the Viewcontroller class is hooked up with the XIB’s File's Owner object, head on over to the Attributes Inspector and change the following settings in the dropdown menus (Size is the most important here):

  • Size - Freeform
  • Orientation - Inferred
  • Status Bar - None
  • Top Bar - None
  • Bottom Bar - Inferred

Got that? Awesome. So Freeform is important to allow changing the size of the layout.

STEP TWO: Adding a simple button to trigger the resize

Next, let’s go ahead and add a button to the view. For this example, it doesn’t have to be fancy at all. Then, bind the button to your ViewController with an @IBAction func. For example, here is mine:

 @IBAction func onExpandoClick(sender: AnyObject) {
        self.resizeXib(); // or any other custom method here
    }

STEP THREE: The resize function!

Finally, we will create a simple function to resize your XIB.

    func resizeXib(){
        var testRect: CGRect = self.myXibView.frame
        testRect.size.height = 400;
        self.myXibView.frame = testRect;
    }

DONE!

That’s all there is to it; on your button click the XIB will resize to 400! Obviously there are a lot of customizations you can make here including animations, etc. But there you go! If you have any questions, feel free to reach out patrickcanella at gmail dot com!