Reputation: 107
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?
Upvotes: 1
Views: 1651
Reputation: 205
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
Upvotes: 1