I've been looking around for a while now but can't seem to work out how to stop the collection view cells from consuming the touch events.
I need the touch events to be passed down into the respective cells so that the buttons within the cells can be pressed. I was thinking i might need to work out how to disable the UICollectionView's didSelectCellAtIndexFunction?
I've also seen this as a potential solution: collectionView.cancelsTouchesInView = false
Also this link might help someone answer my question: How to add tap gesture to UICollectionView , while maintaining cell selection?
Thanks in advance!
Edit:
Also I should add: my buttons are added to a view that is in turn added to the cell's contentView. My code is done all programatically and so I am not using interface Builder at all.
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return false // all cell items you do not want to be selectable
}
Assuming all buttons are connected to the same selector, you need a way to differentiate which cell's button has been clicked. One of the ways for finding out the button's cell's index is:
func buttonPressed(button: UIButton) {
let touchPoint = collectionView.convertPoint(.zero, fromView: button)
if let indexPath = collectionView.indexPathForItemAtPoint(touchPoint) {
// now you know indexPath. You can get data or cell from here.
}
}
Try on your cell.
self.contentView.isUserInteractionEnabled = false
Related
I am working on a project and one of the table views the text for it is a UITextView, but on the other one is a UILabel. The UILabel detects the click from the user as a click on the table cell, but the UITextView doesn't. Why is this happening? Is there any way to fix it?
Try that
yourTextView.addTarget(self, action: #selector(myTargetFunction), for: .touchDown)
#objc func myTargetFunction(textField: UITextView) {
print("myTargetFunction")
}
Ensure the isSelectable property of your textView is true.
I figure it out, the cell view and text view are both scrow views and always will have conflict, so I need to uncheck the UserInteractions and Multiple Touch of the text view, booth set to false
I'm not sure from your question whether you're talking about selection on the UITableView row or the UITextView/UILabel itself.
If you're trying to set up a gesture recognizer on the UILabel or UITextView, I'm wondering if that's necessary or if you could just use didSelectRowAtIndexPath in your view controller.
e.g.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
yourMethodHere(for: cell)
}
Then you'd define in yourMethodHere() what behavior you want to happen when the cell is selected.
I'm facing a weird issue in UICollectionView using iOS11 emulator. In my project i have a UICollectionView with UIImageView as cells and I've created segue as Triggered Segues for cells by dragging it to a view controller. It was working great but know the segue is not performing so i decided to remove the segue from cells Triggered Segues and I created a segue from my view controller to the destination view controller and performed segue from code
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
if let url = URL(string: "\(StringResources.serverAddress)/Content/images/Files/Thumb/\(photos[indexPath.row])") {
cell.image.downloadFrom(url: url)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("clicked")
performSegue(withIdentifier: "PhotoSegue", sender: collectionView.cellForItem(at: indexPath))
}
but it's not working either and there is no clicked printed in console. I've checked cell and UIImageView user interaction also UICollectionView delegate is ok. How can i fix it?
edit: I've found the problem. It's only calling when I'm double clicking on cell
There are some things that you could check and once all of them are in order it should work:
Check that your UICollectionView has both delegate and dataSource set.
Check that your UIImageView userInteractionEnabled property is set to false.
According to documentation:
Image views ignore user events by default. Normally, you use image views only to present visual content in your interface. If you want an image view to handle user interactions as well, change the value of its isUserInteractionEnabled property to true. After doing that, you can attach gesture recognizers or use any other event handling techniques to respond to touch events or other user-initiated events.
Check that both UICollectionView and parent have. userInteractionEnabled property is set to true.
Check that there are no other UIGestureRecognizers catching your touch event.
Check that there are no network requests freezing your UI.
Considering the information that you provided, I would try to remove the UIImageView from the cell and make sure that the cell touch is working before adding more elements.
the problem is that I was adding a UITapGestureRecognizer to dismiss the keyboard and that was catching touch events.
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)
}
The issue could be due to the fact that collection views have a didSelectItemAt method as well as a didDeselectItemAt method which alternate per click. This could explain why it only works on a double click (one click calls didSelect, the next calls didDeselect).
A quick (but not elegant) solution could be to implement your didDeselectItemAt and just use it to call the didSelectItemAt
I made a horizontal scrolling UICollectionView and I want the cell that's in the middle to have a white font while the rest is black.
If I just use scrollViewDidEndDecelerating highlighting of the middle cell seems to jump around more than if I use both scrollViewWillBeginDecelerating and scrollViewDidEndDecelerating to highlight the middle cell. Is this bad practice?
extension CurrencySelectorTableViewCell: UIScrollViewDelegate{
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
self.findCenterIndex()
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.findCenterIndex()
}
}
This code btw still doesn't animate perfectly like I want it to so I'm open to any advice how to make this scrolling mechanism as smooth as possible.
When the UICollectionView thus starts scrolling this function is triggered:
func findCenterIndex() {
let center = self.convert(self.collectionView.center, to: self.collectionView)
let index = collectionView!.indexPathForItem(at: center)
if let selectedIndex = index {
self.selectedCell = selectedIndex.item
self.collectionView.reloadData()
}
}
Upon reloading the UICollectionView the label in the cell that is located in the middle will look different from the rest:
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CurrencySelectorCollectionViewCell", for: indexPath) as! CurrencySelectorCollectionViewCell
if (indexPath.item == self.selectedCell) {
cell.currencyLabel.textColor = UIColor.white
cell.currencyLabel.font = cell.currencyLabel.font.withSize(22)
} else {
cell.currencyLabel.textColor = UIColor.black
cell.currencyLabel.font = cell.currencyLabel.font.withSize(15)
}
cell.currencyLabel.text = currencies[indexPath.item]
return cell
}
Right now it jumps around a little bit because it will only change the label when the scrolling has just started or just stopped. I would like this effect on the UITextLabel to happen continuously throughout the scrolling process.
Try to add removeAllAnimations() of your UILabel layer before you fire off a new animation:
[view.layer removeAllAnimations];
EDIT:
Based on your edit in the question, you are not running any animation. You are calling reloadData on your UICollectionView, which is really bad practice.
You should just simple either:
1: (Bad option)
Reload the Cell only with performBatchUpdates(_:completion:)
2: Good option
Access the cell as a variable in your cell findCenterIndexwith cellForItem(at:) and simply just do your update to the label.
You can also deselect the other cells by getting an array of the visibleCells and simply just do as same described above, but you fire your "deselection" code instead. You could actually do this before you run your selection code. Or do everything in one action by Simply run a for loop on the visible cells and "deselect" them in your loop, and select the one in your CGPoint center.
This way, you never even have to reload your UICollectionView and is the best practice. And you also avoid flickers and animations.
I am making an iOS app that relies on a table view. In each cell of the table view, there are 4 buttons aligned on the bottom. I have a cell class that is pretty standard and a feedController to handle the table and setting all the items of the cell.
Everything works fine on it but I can not figure out how to handle the button clicks within the cell. I can hard code it into my cell class, but then every 3 cells has the same interaction. Is there a way to pass the button click function from the cell class into the controller? I have tried checking the state from the controller and that has not worked.
Can you add a gesture recognizer as you're doing your cellForItemAtIndexPath? So I had something similar with a collection view, and what I did was as it within:
func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!
{
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as MyCollectionView
...
I would add a gesture recognizer to each cell
i.e.
cell.addGestureRecognizer(UITapGestureRecognizer(target: self, action:Selector("tapAction:")))
And then something like:
func tapAction(recognizer: UITapGestureRecognizer) {
...
}
so recognizer ends up being the specific item tapped, and I could take action accordingly (in my case, I had my datasource of items and I would find the item in an array by casting recognizer to a cell, finding the appropriate subview, and update values on it)
I would add code block properties to your cell class which the table can assign to deal with each button. In your cell, code each button handler to call the appropriate block, or pass an index for the button used in a single block.
See my answer here which has an example, but for a switch.
How can I get index path of cell on switch change event in section based table view
If after a few cells you get the same interaction, it's possibly because you're dequeueing a reusable cell, and you're getting the same cell.
Make sure to set your .setTarget() call for your buttons in your tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) data source every time the cell is dequeued. It would help if you shared how you're handling dequeuing to see if this is your issue.
I need the user to be able to reorder a UITableView by this way: he touches a cell for a predetermined period (e.g. 1 second), then he can drag and drop it over the other cells.
I know how to implement the 'long touch' detection using a gesture recognizer, but what is the best way to implement the drag and drop ability without using a reorder control (the user should drag the cell from anywhere in the cell, not only from the reorder control)?
This is an old question, but here's a solution that's tested and working with iOS 8 through 11.
In your UITableViewCell subclass try this:
class MyTableViewCell: UITableViewCell {
weak var reorderControl: UIView?
override func layoutSubviews() {
super.layoutSubviews()
// Make the cell's `contentView` as big as the entire cell.
contentView.frame = bounds
// Make the reorder control as big as the entire cell
// so you can drag from everywhere inside the cell.
reorderControl?.frame = bounds
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: false)
if !editing || reorderControl != nil {
return
}
// Find the reorder control in the cell's subviews.
for view in subviews {
let className = String(describing: type(of:view))
if className == "UITableViewCellReorderControl" {
// Remove its subviews so that they don't mess up
// your own content's appearance.
for subview in view.subviews {
subview.removeFromSuperview()
}
// Keep a weak reference to it for `layoutSubviews()`.
reorderControl = view
break
}
}
}
}
It's close to Senseful's first suggestion but the article he references no longer seems to work.
What you do, is make the reorder control and the cell's content view as big as the whole cell when it's being edited. That way you can drag from anywhere within the cell and your content takes up the entire space, as if the cell was not being edited at all.
The most important downside to this, is that you are altering the system's cell view-structure and referencing a private class (UITableViewCellReorderControl). It seems to be working properly for all latest iOS versions, but you have to make sure it's still valid every time a new OS comes out.
I solved the question of the following steps:
Attach gesture recognizer to UITableView.
Detect which cell was tapped by "long touch". At this moment create a snapshot of selected cell, put it to UIImageView and place it on the UITableView. UIImageView's coordinates should math selected cell relative to UITableView (snapshot of selected cell should overlay selected cell).
Store index of selected cell, delete selected cell and reload UITableView.
Disable scrolling for UITableView. Now you need to change frame of snapshot UIImageView when you will drag cell. You can do it in touchesMoved method.
Create new cell and reload UITableView (you already have stored index) when the user finger leaves screen.
Remove the snapshot UIImageView.
But it was not easy to do it.
The article Reordering a UITableViewCell from any touch point discusses this exact scenario.
Essentially you do the following:
Find the UITableViewCellReorderControl (a private class).
Expand it so it spans the entire cell.
Hide it.
The user will now be able to drag the cell from anywhere.
Another solution, Cookbook: Moving Table View Cells with a Long Press Gesture, achieves the same effect by doing the following:
Add a long press gesture recognizer on the table view.
Create a snapshot of the cell when the cell is dragged.
As the cell is dragged, move the snapshot around, and call the -[UITableView moveRowAtIndexPath:toIndexPath:].
When the gesture ends, hide the cell snapshot.
For future reference...
I had the same problem, I found another question(Swift - Drag And Drop TableViewCell with Long Gesture Recognizer) about it and someone suggested this tutorial: https://www.freshconsulting.com/create-drag-and-drop-uitableview-swift/
worked just perfectly for me
I know this is a question about UITableView. But I ended with a solution of using UICollectionView rather than UITableView to implement longtap reorder. Its easy and simple.
tableView.dragInteractionEnabled = true
tableView.dragDelegate = self
tableView.dropDelegate = self
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { }
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession,
at: indexPath: IndexPath) -> [UIDragItem] {
return [UIDragItem(itemProvider: NSItemProvider())]
}
func tableView(_ tableView: UITableView, dropSessionDidUpdate session:
UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
if session.localDragSession != nil {
return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}
return UITableViewDropProposal(operation: .cancel, intent: .unspecified)
}
func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
}