Reputation: 363
I am trying to save the text of a cell within my UITableView
for later usage. I saw on a different Stack Overflow posts it was recommended to use
sender.view
when I print it out to the console, the respose is:
Optional(<UITableViewCell: 0x7f8e0a803400; frame = (0 0; 375 50); text = 'Event 1'; clipsToBounds = YES; autoresize = W; gestureRecognizers = <NSArray: 0x60400024f150>; layer = <CALayer: 0x60400002b940>>)
However when I try to access
sender.view?.text
XCode shows an error saying
Value of type 'UIView' has no member 'text'
I have not found any ways to get the text from a UIView, is it even possible, if so how? Thanks in advance!
Edit:
sender is a UITapGestureRecognizer
I am passing into the method from the button press
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
cell.textLabel?.text = mydata[indexPath.item]
cell.addGestureRecognizer(tapGesture)
cell.isUserInteractionEnabled = true
return cell
}
@objc func handleTapGesture(sender: UITapGestureRecognizer) {
performSegue(withIdentifier: "SegueToScanner", sender: self)
}
Upvotes: 0
Views: 1110
Reputation: 257
Not sure why're using a tap gesture recognizer over a tableView cell. Here's another solution which might be of use to you.
You can use
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
delegate method from UITableViewDelegate
In your case it should look something like this.
extension YourViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? UITableViewCell {
let text = cell.textLabel?.text
}
}
Make sure your ViewController
conforms to UITableViewDelegate
in viewDidLoad
Upvotes: 0
Reputation: 751
Try to cast the sender.view as a UITableViewCell, then you should be able to access the cell's textLabel.
guard let cell = sender.view as? UITableViewCell else {
//error handling
return
}
let text = cell.textLabel.text
Upvotes: 1