Reputation: 2745
I've one UITableView
with 5 Sections and multiple different rows within each section.
My code for add UISwitch
into TableView
switchForNotification = [[UISwitch alloc]initWithFrame:CGRectMake(300, 10, 100, 40)];
[switchForNotification addTarget:self action:@selector(Notification) forControlEvents:UIControlEventValueChanged];
switchForNotification.on = NO;
[cell.contentView addSubview:switchForNotification];
So, it'll add into TableViewCell.
But, when I'm scrolling, Table is reloading accordingly with UITableView methods and switch will be added into other cells.
I want to prevent this issue of adding automatically custom controls into cell while scrolling and reloading.
How can I do that ?
Any suggestions will be appreciated.
Thanks in advance.
Upvotes: 1
Views: 558
Reputation: 797
if (cell==nil){cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier]; }
Upvotes: 0
Reputation: 46
You can Make one custom cell which contains one UILable ,UISwitch and UIImageview...
Now as per indexpath.row show and hide this subview as per you needs.
Upvotes: 3
Reputation: 26652
What you need to do is have several different instances of UITableViewCell
depending on how many different types of table view cell you have.
Each is assigned a reuse identifier.
Then, in cellForRowAtIndexPath
, depending on the section or row of indexPath
, you dequeue the appropriate cell, set whatever data, and return that.
So, for example, assuming you have three types of cell for switch, image, and other, you would dequeue as follows:
static NSString *kCellReuseIdentifierSwitch = @"SwitchCell";
static NSString *kCellReuseIdentifierImage = @"ImageCell";
static NSString *kCellReuseIdentifierOther = @"OtherCell";
if (indexPath.row == 0)
{
MySwitchCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellReuseIdentifierSwitch forIndexPath:indexPath];
}
else if (indexPath.row == 1)
{
MyImageCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellReuseIdentifierImage forIndexPath:indexPath];
}
else if (indexPath.row == 2)
{
MyOtherCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellReuseIdentifierOther forIndexPath:indexPath];
}
This example assumes iOS 6 or above where cell instantiation is handled for you by the dequeue
method.
Upvotes: 0
Reputation: 1292
Try this code. Add this code in your cellFotRowAtIndexPath
NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
for (UIView *subview in subviews)
{
if([subview isKindOfClass:[UIView class]])
[subview removeFromSuperview];
else if([subview isKindOfClass:[UIImageView class]])
[subview removeFromSuperview];
else if([subview isKindOfClass:[UILabel class]])
[subview removeFromSuperview];
else if([subview isKindOfClass:[UISwitch class]])
[subview removeFromSuperview];
}
[subviews release];
Upvotes: 2