Resize a UITableView

4.7k views Asked by At

I have a Tableview with above it a Segmented Controller. Based on a previous user action, this segmented controller is either hidden or shown.

If it's hidden, I'd like to resize my tableview, so that it looks nice (else I have an empty gap on the screen).

enter image description here

I tried the following code (placed in the ViewDidLoad) but it did not work. It also didn't work when placed in the ViewDidAppear or other functions. The Tableview is referenced from the Storyboard, its not programmatically created.

    if selectedGroup == 1
    {
        self.tableView.frame = CGRectMake(0, 152, 320, 367)
        segControl.hidden = false
    }
    else if selectedGroup == 2
    {
        self.tableView.frame = CGRectMake(0, 116, 320, 403)
        segControl.hidden = true
    }

I tried some other stuff like working with offsetting the frame and then adjusting the height, but that didn't work either...

3

There are 3 answers

1
Duncan C On BEST ANSWER

My first guess was that you were using AutoLayout. Changes to view frames often don't have any effect in that case. Have you double-checked to make sure it's turned off for you storyboard?

Failing that, the most likely cause of changing having no effect is broken outlets. Add a println to display self.tableView (or set a breakpoint and examine it from the debugger) and make sure it's not nil.

BTW, using constant values for your sizes ("magic numbers") is a bad idea. That code will only work on a single screen size, and will break if you make any changes to your layout.

You should write your code to be flexible. Calculate the frame based on the size of the view controller content view, or the previous frame size.

2
Ashish Kakkad On

With Autolayout

If you are using Autolayout and if you want to change the frame then try the constraints (IBOutlet of NSLayoutConstraint).

enter image description here

Set the constraint outlets and change constant value by :

self.sampleConstraint.constant = 20
self.view.layoutIfNeeded()

Without Autolayout

Use autoresizing form utilities

enter image description here

You can also do it by code (obj-c) :

view.autoresizingMask = (UIViewAutoresizingFlexibleWidth |    
                              UIViewAutoresizingFlexibleLeftMargin);
0
TheNiers On

I found a workaround. If you want to use auto-layout but still have the ability to resize certain views on runtime, you can call viewDidLayoutSubviews. This gets called after all constraints are placed, but before the viewDidAppear is called, so the user doesn't even notice

override func viewDidLayoutSubviews() {
    if catswitch == "1"
    {
        self.tableView.frame = CGRectMake(0, 152, 320, 367)
        scMatur.hidden = false
    }
    else if catswitch == "2"
    {
        self.tableView.frame = CGRectMake(0, 116, 320, 403)
        scMatur.hidden = true
    }
}

See Can I disable autolayout for a specific subview at runtime? for original answer by jmstone.