Reputation: 358
I have a dynamic cell inside a TableView that automatically sizes based the info in a TextView. This happens inside a tableView: didSelectRowAt function. A simplified version is below:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? cell else { return }
if cell.textViewOutlet.attributedText.length != 12 {
cell.textViewOutlet.attributedText = NSMutableAttributedString(
string: "Expand:\n\n\n " + String(indexPath.row)
)
} else {
cell.textViewOutlet.attributedText = NSMutableAttributedString(
string: "Cell: " + String(indexPath.row)
)
}
This shows as on the following image:
In the image Cell 1 is expanded, Cell 0 and 2 are compressed. With this setup I can have the user alternate between expanding and compressing the cell (and the message) by selecting the cell.
My problem is I want to give the user the ability to edit the text. Of course, when the user clicks to edit the "didSelectRowAt" function is entered.
What is the best way to differentiate the edit action from the expand action? Can I make the action some multi-touch or long touch action?
One constraint is that whatever touch method that would work in the textView would also have to be used in other cells on the app that do not have these expand capabilities. Therefore, it would be cleaner if I can use another technique to expand.
Upvotes: 1
Views: 249
Reputation: 358
I solved this problem by replacing the didSelectRowAt actions with a pinch gesture to expand the cell or to contract it. Therefore, the textView editing could proceed as normal.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
...
let pinch = UIPinchGestureRecognizer(target: self,
action: #selector(pinchResponse(recognizer:)))
cell.addGestureRecognizer(pinch)
cell.isUserInteractionEnabled = true
return cell
}
@objc func pinchResponse(recognizer: UIPinchGestureRecognizer) {
print("in pinchResponse recognizer.scale: \(recognizer.scale)")
if recognizer.state == UIGestureRecognizer.State.ended {
let pinchLocation = recognizer.location(in: tableView)
if let pinchIndexPath = tableView.indexPathForRow(at: pinchLocation) {
if let pinchedCell = tableView.cellForRow(at: pinchIndexPath) as? StepTableViewCell {
// 2
if recognizer.scale > 1.0 {
print("Expand pinchIndexPart.count: \(pinchIndexPath.count)")
// Add expand actions
print("pinchedCell: \(String(describing: pinchedCell.recipeNbrLabel.text))")
} else {
print("Contract pinchIndexPart.count: \(pinchIndexPath.count)")
// Add contract actions
print("pinchedCell: \(String(describing: pinchedCell.recipeNbrLabel.text))")
}
tableUpdate()
}
}
}
}
Upvotes: 1