So i am trying to get the value of the textLabel of the row I select. I tried printing it, but it didn't work. After some research I found out that this code worked, but only in Objective-C;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"did select and the text is %@",[tableView cellForRowAtIndexPath:indexPath].textLabel.text);]
}
I could not find any solution for Swift. Printing the indexpath.row is possible though, but that is not what I need.
so what should I do? or what is the 'Swift-version' of this code?
If you want to print the text of a
UITableViewCell
according to its matchingNSIndexPath
, you have to useUITableViewDelegate
'stableView:didSelectRowAtIndexPath:
method and get a reference of the selectedUITableViewCell
withUITableView
'scellForRowAtIndexPath:
method.For example:
However, for many reasons, I would not encourage you to use the previous code. Your
UITableViewCell
should only be responsible for displaying some content given by a model. In most cases, what you want is to print the content of your model (could be anArray
ofString
) according to aNSIndexPath
. By doing things like this, you will separate each element's responsibilities.Thereby, this is what I would recommend:
As you can see, with this code, you don't have to deal with optionals and don't even need to get a reference of the matching
UITableViewCell
insidetableView:didSelectRowAtIndexPath:
in order to print the desired text.Try this:
Maintain an array which stores data in the
cellforindexPath
method itself :-Using same code in the
didselectaAtIndexPath
method too.. Good luck :)Swift 3
Swift 4
To get the label of the selected row:
To get the label of the deselected row:
If you're in a class inherited from
UITableViewController
, then this is the swift version:Note that
cell
is an optional, so it must be unwrapped - and the same fortextLabel
. If any of the 2 is nil (unlikely to happen, because the method is called with a valid index path), if you want to be sure that a valid value is printed, then you should check that bothcell
andtextLabel
are both not nil: