1

I have a static UITableView as shown in the first image, but now I need to add a row with a Button that when I touch it adds a dynamic cell to the table as shown in the second image, the issue is that I can't add new cells to a static UITableview. What would be the best practice to accomplish this?

first image second image

1
  • That means you need a dynamic table view. Or you can use Eureka. Commented Oct 4, 2017 at 16:26

1 Answer 1

1

Basically static TableView is not supposed to be changed at runtime (except cell content). This is clearly mentioned in docs:

Use static cells when a table does not change its layout, regardless of the specific information it displays.

The best practice in this case is to create a dynamic TV and populate it with appropriate amount of cells. You'll need to use DataSource delegate to do so. DataSource itself is typically done through dictionaries or arrays.

E.g. you have a dict 'phoneNumbers' and a button that is supposed to add a new one.

First, you add a selector to the button in cellForRowAtIndexPath: via tag for example. Then button action is going to look like:

-(void)yourButtonClicked:(UIButton*)sender
{
     [self.phoneNumbers setObject:phoneNumber forKey:numberKey];
     [self.tableView reloadData];
}

//Swift
func yourButtonClicked(sender: UIButton) {
   self.phoneNumbers["numberKey"] = phoneNumber
   self.tableView.reloadData()
} 

(sorry it's Obj-C but I'm quite sure swift isn't much different at this point)

reloadData is needed to refresh TableView layout after changes to DataSource objects are made. It's quite close to 'redraw' in this case.

On the image from Contacts App you showed object is '(555)555-5555' NSString and key is probably 'other'. You can use and store these any way you like

So after all you only need to setup numberOfRowsInSection: so that for section where you want to add cells it returns the count of objects in dictionary phoneNumbers

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I understand how to make the section of the phone cells, but which is the best way to make dynamic the current static sections in my tableview. Thanks!
You need to change 'Content' option for TableView in your XIB/Storyboard Attribute Inspector from 'Static Cells' to 'Dynamic prototypes'. Make sure every cell prototype has a unique cell Identifier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.