Correct Way to Setting a Tag to All Cells in Tableview

Correct way to setting a tag to all cells in TableView

My solution to this kind of problem is not to use a tag in this way at all. It's a complete misuse of tags (in my opinion), and is likely to cause trouble down the road (as you've discovered), because cells are reused.

Typically, the problem being solved is this: A piece of interface in a cell is interacted with by the user (e.g. a button is tapped), and now we want to know what row that cell currently corresponds to so that we can respond with respect to the corresponding data model.

The way I solve this in my apps is, when the button is tapped or whatever and I receive a control event or delegate event from it, to walk up the view hierarchy from that piece of the interface (the button or whatever) until I come to the cell, and then call the table view's indexPath(for:), which takes a cell and returns the corresponding index path. The control event or delegate event always includes the interface object as a parameter, so it is easy to get from that to the cell and from there to the row.

Thus, for example:

UIView* v = // sender, the interface object
do {
v = v.superview;
} while (![v isKindOfClass: [UITableViewCell class]]);
UITableViewCell* cell = (UITableViewCell*)v;
NSIndexPath* ip = [self.tableView indexPathForCell:cell];
// and now we know the row (ip.row)

[NOTE A possible alternative would be to use a custom cell subclass in which you have a special property where you store the row in cellForRowAt. But this seems to me completely unnecessary, seeing as indexPath(for:) gives you exactly that same information! On the other hand, there is no indexPath(for:) for a header/footer, so in that case I do use a custom subclass that stores the section number, as in this example (see the implementation of viewForHeaderInSection).]

iOS Table View - Set tag on cell or label?

I'm not familiar with the tutorial, but using tags to identify labels within cells this way is not a good idea.

The cell should know about it's own label. It's far better to just have a method on the cell that you can pass the text to, and then let the cell take care of displaying the text in the cell.

By using the tag in this way, you are expecting to know too much about the internal implementation of the cell, and this is brittle and is likely to break.

So my answer is to set the tag on neither of them, and to use a proper configuration method of the cell itself.

Edited to add

You can download a simple version of a project for configuring a cell, without using tags here https://bitbucket.org/abizern/so-27713743/get/543739690dc4.zip

How to give different tags to buttons in different TableView cells in Swift

Perhaps finally found an issue. When I reproduced the problem in my project, I realised that downcasting to UIButton was missing.

So within HubEntryTableViewCell subclass update the method like this:

@IBAction func plus(sender: AnyObject) {

// self.tag, if called from UITableViewCell subclass, is rather cell's tag, not button's tag

let button = sender as! UIButton
print("button.tag = \(button.tag)")
...
}

tagging buttons in tableview cells

Your problem is because of the cell reuse

Your problem in details

You add the button tag to be 6 in your nib file or storyboard, and so when the table create a new cell it sets the button tag to be 6. Then you are able to get that cell by using

[cell viewWithTag:6]

This will work fine for the first 5 rows (or the first rows displayed before you need to scroll the table).

After you scroll the table the table then will get an "old cell" that is no longer displayed to change its properties however that you have already changed the tag of the button in that cell and so you will not be able to get the button with tag 6 as the button now has tag (1000 + x) which you have previously set that

The solution

Create class for that cell and add an IBOutlet for that button so you can access that cell with the IBOutlet like this

cell.button

Then once you have the button then you can set the tag easily

cell.button.tag = indexPath.row;

How to Set a tag Value in UITAbleView Cell and Pass It into URL in iOS?

The problem is that you're setting intValue to 1 in your cellForRowAtIndexPath: method:

if ([SelectedRows containsObject:obj])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.tag=1;
intValue=cell.tag;
NSLog(@"Tag %d",intValue);
}

That's why intValue always equals 1.

And the solution is NOT to set the intValue equal to 0 in the other conditional of cellForRowAtIndexPath:. Although you're correctly setting your selected cells' tags to 1 and your unselected cells' tags to 0 as you intended, you shouldn't assign your intValue variable in this method. Instead, you should set your intValue depending on the current tag. For example, if there's a save button in each row, you'll want to set that button's tag to 0 or 1 then utilize the parameter in the the button press method to set intValue equal to sender.tag.

Edit: As was made clear in the comments "intValue,intValue,intValue,intValue,intValue,intValue,intValue,intValue,intValu‌​e" used in forming the url are actually supposed to be different numbers, each one representing a different cell's tag. But by using intValue repeatedly like that, you're actually using the same exact value 9 times. You actually need to use 9 different values to do what you're attempting to do.

You can create an array of those 9 values dynamically in cellForRowAtIndexPath:.

In viewDidLoad you can initialize a class NSMutableArray variable with exactly 9 indexes all containing 0:

self.tagArray = [[NSMutableArray alloc] init];
for (int i = 0 ; i < 9 ; i ++) {
[self.tagArray addObject:[NSNumber numberWithInt:0]];
}

Then update those indices in cellForRowAtIndexPath::

-(CategoryCustumCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// ...

NSNumber *obj = [NSNumber numberWithInteger:indexPath.section];
if ([SelectedRows containsObject:obj])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.tag=1;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
cell.tag=0;
}

[self.tagArray replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithInteger:cell.tag]];
return cell;
}

Then during perform save, use the tags stored in your tag array:

- (void)performSave {

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.janvajevu.com/webservice/insert_gcm.php?gcm_id=%@&category1=%@&category2=%@&category3=%@&category4=%@&category5=%@&category6=%@&category7=%@&category8=%@&category9=%@", uniqueIdentifier, self.tagArray[0], self.tagArray[1], self.tagArray[2], self.tagArray[3], self.tagArray[4], self.tagArray[5], self.tagArray[6], self.tagArray[7], self.tagArray[8]]];
}

Use tags for tableView inside UIViewController to update Labels

Your cell is not knowing about your label inside (the one with 500 tag). You are not providing a custom cell, because of this line:

let cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("LineItemCell", forIndexPath: indexPath)

This is a predefined cell. As of documentation you can have predefined cells or custom ones (obtained by subclassing UITableViewCell):

"When creating cells, you can customize them yourself or use one of several predefined styles. The predefined cell styles are the simplest option. With the predefined styles, the cell provides label and image subviews whose positions and styling are fixed. ... To set the text and images of the cell, use the textLabel, detailTextLabel, and imageView properties."

  1. If you want to go predefined:
    If you want to just put the text onto cell use (I see this one is commented on first place).

    cell.textLabel?.text = object["quantity"]

  2. Go custom

Extend UITableViewCell on a separate swift file. Do your bindings here and work with your storyboard in parallel. Assign the custom class to your cell. Also, change dequeue:

let cell: MyCustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("LineItemCell", forIndexPath: indexPath) as! MyCustomTableViewCell

How to get all cells in a UITableView

I don't think thats possible, simply because the tableView doesn't store all cells. It uses a caching mechanism which only stores some cells, that are not visible, for reuse.

Why do you need all cells? Maybe you can achieve, what you're trying to do, otherwise.



Related Topics



Leave a reply



Submit