I have the tag for a custom UITableViewCell but I am not sure how I should reference it?
What is the standard approach here.
I thought something close to this but of course this will not work right?:
CustomCell *cell = (CustomCell*)[self.mainTableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:tag inSection:0]];
I make this reference when a button is pressed in the custom implementation of that cell using a delegate method to pass it to my view controller.
You should not refer to cell itself, because is just interface to show your data. Cells can be (and should be) reused and filled with different data.
Better is store data id, or at lest index of element that cell.
Read more in docs A Closer Look at Table View Cells
To get from a button in a cell to the cell itself, walk up the view hierarchy:
UIView* v = sender; // sender is the button that was tapped
do {
v = v.superview;
} while (![v isKindOfClass: [UITableViewCell class]]);
DiscoverCell* cell = (DiscoverCell*)v;
Related
I'm using a button inside a tableView in which I get the indexPath.row when is pressed. But it only works fine when the cells can be displayed in the screen without scroll.
Once the tableView can be scrolleable and I scrolls throught the tableview, the indexPath.row returned is a wrong value, I noticed that initially setting 20 objects, for example Check is just printed 9 times no 20.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
lBtnWithAction = [[UIButton alloc] initWithFrame:CGRectMake(liLight1Xcord + 23, 10, liLight1Width + 5, liLight1Height + 25)];
lBtnWithAction.tag = ROW_BUTTON_ACTION;
lBtnWithAction.titleLabel.font = luiFontCheckmark;
lBtnWithAction.tintColor = [UIColor blackColor];
lBtnWithAction.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
[cell.contentView addSubview:lBtnWithAction];
}
else
{
lBtnWithAction = (UIButton *)[cell.contentView viewWithTag:ROW_BUTTON_ACTION];
}
//Set the tag
lBtnWithAction.tag = indexPath.row;
//Add the click event to the button inside a row
[lBtnWithAction addTarget:self action:#selector(rowButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
//This is printed just 9 times (the the number of cells that are initially displayed in the screen with no scroll), when scrolling the other ones are printed
NSLog(#"Check: %li", (long)indexPath.row);
return cell;
}
To do something with the clicked index:
-(void)rowButtonClicked:(UIButton*)sender
{
NSLog(#"Pressed: %li", (long)sender.tag);
}
Constants.h
#define ROW_BUTTON_ACTION 9
What is the correct way to get the indexPath.row inside rowButtonClicked or setting a tag when I have a lot of of cells in my 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).]
I agree with #matt that this is not a good use of tags, but disagree with him slightly about the solution. Instead of walking up the button's superviews until you find a cell, I prefer to get the button's origin, convert it to table view coordinates, and then ask the table view for the indexPath of the cell that contains those coordinates.
I wish Apple would add a function indexPathForView(_:) to UITableView. It's a common need, and easy to implement. To that end, here is a simple extension to UITableView that lets you ask a table view for the indexPath of any view that lies inside one of the tableView's cells.
Below is the key code for the extension, in both Objective-C and Swift. There is a working project on GitHub called TableViewExtension-Obj-C that illustrates the uses of the table view extension below.
EDIT
In Objective-C:
Header file UITableView_indexPathForView.h:
#import <UIKit/UIKit.h>
#interface UIView (indexPathForView)
- (NSIndexPath *) indexPathForView: (UIView *) view;
#end
UITableView_indexPathForView.m file:
#import "UITableView_indexPathForView.h"
#implementation UITableView (UITableView_indexPathForView)
- (NSIndexPath *) indexPathForView: (UIView *) view {
CGPoint origin = view.bounds.origin;
CGPoint viewOrigin = [self convertPoint: origin fromView: view];
return [self indexPathForRowAtPoint: viewOrigin];
}
And the IBAction on the button:
- (void) buttonTapped: (UIButton *) sender {
NSIndexPath *indexPath = [self.tableView indexPathForView: sender];
NSLog(#"Button tapped at indexpPath [%ld-%ld]",
(long)indexPath.section,
(long)indexPath.row);
}
In Swift:
import UIKit
public extension UITableView {
func indexPathForView(_ view: UIView) -> IndexPath? {
let origin = view.bounds.origin
let viewOrigin = self.convert(origin, from: view)
let indexPath = self.indexPathForRow(at: viewOrigin)
return indexPath
}
}
I added this as a file "UITableView+indexPathForView" to a test project to make sure I got everything correct. Then in the IBAction for a button that is inside a cell:
func buttonTapped(_ button: UIButton) {
let indexPath = self.tableView.indexPathForView(button)
print("Button tapped at indexPath \(indexPath)")
}
I made the extension work on any UIView, not just buttons, so that it's more general-purpose.
The nice thing about this extension is that you can drop it into any project and it adds the new indexPathForView(_:) function to all your table views without having do change your other code at all.
You are running into the issue of cell-reuse.
When you create a button for the view you set a tag to it, but then you override this tag to set the row number to it.
When the cell get's reused, because the row number is longer ROW_BUTTON_ACTION, you don't reset the tag to the correct row number and things go wrong.
Using a tag to get information out of a view is almost always a bad idea and is quite brittle, as you can see here.
As Matt has already said, walking the hierarchy is a better idea.
Also, your method doesn't need to be written in this way. If you create your own custom cell, then the code you use to create and add buttons and tags isn't needed, you can do it in a xib, a storyboard, or even in code in the class. Furthermore, if you use the dequeue method that takes the index path, you will always get either a recycled cell, or a newly created cell, so there is no need to check that the cell returned is not nil.
I've created a UIButton dynamically in the table view cell. but there is a problem,- I'm not able to access the button or it's sender method.
When I click on a button it's giving the wrong tag or sometime it's not clickable. I've created button a with the help of for() loop in the tableview cell. I think the main problem is that I create the button in the for() loop. Can anyone help me to solve this issue?
My code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIView *viewDisplaySize;
if (cell == nil)
{
NSString *myString =#"1111111:2222222:333333:44444:55555:6666:777777:888888888888:9999999999" ;
NSArray *myWords = [myString componentsSeparatedByString:#":"];
for (int i=0; i < [myWords count]; i++) {
//Create a button but can't able to get a correct tag
/// Or some time it's not click able
}
Whole code--- link of full code
The basic problem is that the way you're adding your subviews is not the best way. By adding the subviews inside a if(cell == nil) clause, and setting the tag value there, the tag value will never change. When the cell is reused, the tag will still be based on the row where it was created, not on where that reused cell now appears.
A better way to create your cell, would be to add any subviews you need in the init method of a custom cell class. This cleans up the code in cellForRowAtIndexPath so it only contains code you need to populate the cells. If the cell is made completely in code (no xib or storyboard for its view), then you should register the class (usually done in viewDidLoad of the table view controller) with registerClass:forCellReuseIdentifier:. Then, in cellForRowAtIndexPath there will be no need to check whether the cell is nil because it never will be. You still want to set the button's action and tag in cellForRowAtIndexPath, but now it will be reset for the proper row when the cell is reused.
I'm creating an app which contains a screen that shows a table view with custom cells. Each cell contains two labels and a subview, which further contains other subviews. I'm handling the click event on the cell to hide/show the subviews within the subview in the cell. How can I make it so that when I click on a single cell, the subview of all the cells will change?
It is like the Stock application in iPhone (using iOS 7), here is a screenshot:
As in the image above, when you click on any of the green box, all the boxes change to reflect the same type of value.
Please let me know if this approach is fine, or how this can be implemented.
There are a couple ways of doing this. The first that comes to mind would be to handle the different states within the UITableViewCell subclass, and just reload the visible cells:
[self.tableView reloadRowsAtIndexPaths:[self.tableView indexPathsForVisibleRows] withRowAnimation:UITableViewRowAnimationAutomatic];
If you're looking for more control over the process though, this process could also be achieved by changing the state future cells should load into, and then calling a method on every visible cell. This would provide you with an easy way to have complete control over how the contents of the cell update.
// Change flag for cell state then...
for (NSIndexPath *indexPath in [self.tableView indexPathsForVisibleRows]) {
if (condition) {
MyCellSubclass *cell = (MyCellSubclass *)[self.tableView cellForRowAtIndexPath:indexPath];
[cell someMethodWithArg:(id)state];
}
}
To do something as in Stock app you should handle two method cellForRowAtIndexPath: and click action method.
In cellForRowAtIndexPath: you should do the check which cell/button was pressed and display value base on it:
//Pseudo code
//cellForRowAtIndexPath
if (cellNo3Pressed)
{
//set up text with the right value.
}
else if (otherCell)
{
//set up text with the right value.
}
This will handle the cell which are not visible on the screen.
The next action method should handle nice animation on all of the visible cell:
NSArray *paths = [tableView indexPathsForVisibleRows];
for (NSIndexPath *path in paths)
{
UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:path];
//Animate changes for cell
}
I have a UITextField in a custom cell inside table. I created new class DataCell which is subclass of UITableViewCell. Inside DataCell I created outlets for textfields and I also have method inside implementation file which uses 'editing did end' and I manipulate textField values there.
I am now wondering how to get rowIndex or number of the cell, as each time I click + button new custom cell is loaded on the table. If I get tag I always get same tag number regardless of the cell I selected.
The text field passed to your delegate is a subview of the cell's contentView.
UITableViewCell *cell = (UITableViewCell*) textField.superview.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
You can use this logic when you are not sure of hierarchy between textfield and cell.
UITableViewCell *cell = nil;
UIView *parentView = textField.superview;
while(parentView) {
if([parentView isKindOfClass:[UITableViewCell class]]) {
cell = parentView;
break;
}
parentView = parentView.superview;
}
if(cell)
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
Add tags to the text field in the tableView:cellForRowAtIndexPath: method. In this example, I have a custom cell with a label and a text field:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RDCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.label1.text = self.theData[indexPath.row];
cell.textField.tag = indexPath.row;
return cell;
}
It sounds like you are maybe handling the end of editing in your custom cell class, but you might want to consider doing it in the table view controller instead, since that gives you easy access to the model, which I presume you are modifying with what the user types in the text field. If you do that, then you should connect the text field's delegate property up to the table view controller in IB.
If we're accepting fragile answers then for the sake of contributing something new to the conversation:
CGRect rectInTableView =
[tableView convertRect:textField.bounds fromView:textField];
NSUInteger indexOfCellContainingTextField =
(NSUInteger)(rectInTableView.y / tableView.rowHeight);
Assumptions that make it fragile: (i) all rows are the same height; (ii) the height is set on the table view. If you haven't implemented UITableViewDelegate -tableView:heightForRowAtIndexPath: then both of those assumptions will hold true. You're also taking advantage of the fact that casting a positive float to an integer rounds down.
I would argue that although still not completely clear of assumptions, this is less fragile than Mundi's solution because it makes assumptions only about things you do directly control (ie, cell sizing) and not about things you don't (ie, the view hierarchy UIKit uses internally to present table views).
I have a table view with custom cells. Cells have an image view, a label and a progress view. What I want to achieve is to update progress view in a specific cell according to the event that fires. My idea is to find the cell by name label that is in the event and then update progress view. This may not be an efficient way but I couldn't think of some other way. Other ideas are also appreciated. Thanks in advance.
You could use a NSDictionary with the name as the key and the NSIndexPath as the object. Then to can look up the index path for a given cell using the name in the dictionary.
UITableView has a 'cellForRowAtIndexPath:` method that should give you the cell for a specific row.
i.e. something like
// Get visible cell for data item
NSInteger row = [myArrayOfThings indexOfObject:thing];
NSIndexPath *inedexPath = [NSIndexPath alloc] initWithRow:row section:0];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indeexPath];
// Update cell here ...
...
Disclaimer : Code typed from memory - you may have to look at the documentation for some of the method names :)
the more better way is with tag,
you can give each cell a unique tag and access that cell by this method
//method of UIView(UIViewHierarchy)
- (UIView *)viewWithTag:(NSInteger)tag;
// can be used like this
UITableViewCell *cell = (UITableViewCell*)[tableView viewwithtag:tag];