I am building a tvos application. i have a strange bug where UICollectionView lose focus of the previously selected cell when i navigate back to that particular view. The scenario is some thing this like this.
I have two UIViewControllers A and B. A has a UITableView and it has three prototype cells in it. Each cell has a horizontal scrolling UICollectionView inside it. When i click on any of UICollectionViewCell it navigates to the B (detail page). I am presenting B modally.
Now when i press Menu button on Siri remote view A appears again (in other words view B is removed from View hierarchy) but the current selected cell is different then the previously selected. I have tried to use remembersLastFocusedIndexPath with both true and false values and also tried by implementing
func indexPathForPreferredFocusedViewInCollectionView(collectionView: UICollectionView) -> NSIndexPath?
but the control neves comes to this function when i navigate back to view A. I am also reloading every thing in viewWillAppear function.
Can any one help me in this. Thanks
The property remembersLastFocusedIndexPath should be set to true for the collectionView and false for the tableView.
Also, Are you reloading the UITableView in viewWillAppear i.e Is the table data being refreshed when the B is popped and A appears?
If Yes, then lastFocusedIndexPath will be nil on reload.
We faced the same issue. We solved it by not reloading the contents when B is popped.
Maintain a flag say didPush. Set this flag to true when B is pushed. When A appears check whether the flag is set and only then fetch data and reload table.
This worked for us.
I don't remember exactly, but I know there was a known issue for remembersLastFocusedIndexPath where it wasn't working as intended.
This is one workaround, although take it with a grand of salt as it does seem slightly hacky and it uses the common (but potentially unstable) approach of overriding the preferredFocusedView property.
private var viewToFocus: UIView?
override var preferredFocusView: UIView? {
get {
return self.viewToFocus
}
}
Save locally the indexPath of the last cell in View A when presenting View B
// [1] Saving and scrolling to the correct indexPath:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
...
collectionView.scrollToItemAtIndexPath(indexPath:, atScrollPosition:, animated:)
}
// [2] Create a dispatchTime using GCD before setting the cell at indexPath as the preferredFocusView:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
...
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(CGFloat.min * CGFloat(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
self.viewToFocus = collectionView.cellForItemAtIndexPath(indexPath:)
// [3] Request an update
self.setNeedsFocusUpdate()
// [4] Force a focus update
self.updateFocusIfNeeded()
}
}
The reason we split the two methods into both viewWillAppear and viewDidAppear is that it eliminates a bit of the animation jump. If anyone else could jump in with suggestions to improve or even alternate solutions, I'd also be interested!
In Swift
If you want to focus collection view Cell then
You can use collectionview Delegate method, method name is
func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator)
{
}
You can use this method like this...
func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
if let previousIndexPath = context.previouslyFocusedIndexPath,
let cell = collectionView.cellForItemAtIndexPath(previousIndexPath) {
cell.contentView.layer.borderWidth = 0.0
cell.contentView.layer.shadowRadius = 0.0
cell.contentView.layer.shadowOpacity = 0
}
if let indexPath = context.nextFocusedIndexPath,
let cell = collectionView.cellForItemAtIndexPath(indexPath) {
cell.contentView.layer.borderWidth = 8.0
cell.contentView.layer.borderColor = UIColor.blackColor().CGColor
cell.contentView.layer.shadowColor = UIColor.blackColor().CGColor
cell.contentView.layer.shadowRadius = 10.0
cell.contentView.layer.shadowOpacity = 0.9
cell.contentView.layer.shadowOffset = CGSize(width: 0, height: 0)
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: [.CenteredHorizontally, .CenteredVertically], animated: true)
}
}
Related
First let me say this seems to be a common question on SO and I've read through every post I could find from Swift to Obj-C. I tried a bunch of different things over the last 9 hrs but my problem still exists.
I have a vc (vc1) with a collectionView in it. Inside the collectionView I have a custom cell with a label and an imageView inside of it. Inside cellForItem I have a property that is also inside the the custom cell and when the property gets set from datasource[indePath.item] there is a property observer inside the cell that sets data for the label and imageView.
There is a button in vc1 that pushes on vc2, if a user chooses something from vc2 it gets passed back to vc1 via a delegate. vc2 gets popped.
The correct data always gets passed back (I checked multiple times in the debugger).
The problem is if vc1 has an existing cell in it, when the new data is added to the data source, after I reload the collectionView, the label data from that first cell now shows on the label in new cell and the data from the new cell now shows on the label from old cell.
I've tried everything from prepareToReuse to removing the label but for some reason only the cell's label data gets confused. The odd thing is sometimes the label updates correctly and other times it doesn't? The imageView ALWAYS shows the correct image and I never have any problems even when the label data is incorrect. The 2 model objects that are inside the datasource are always in their correct index position with the correct information.
What could be the problem?
vc1: UIViewController, CollectionViewDataSource & Delegate {
var datasource = [MyModel]() // has 1 item in it from viewDidLoad
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCell, for: indexPath) as! CustomCell
cell.priceLabel.text = ""
cell.cleanUpElements()
cell.myModel = dataSource[indexPath.item]
return cell
}
// delegate method from vc2
func appendNewDataFromVC2(myModel: MyModel) {
// show spinner
datasource.append(myModel) // now has 2 items in it
// now that new data is added I have to make a dip to fb for some additional information
firebaseRef.observeSingleEvent(of: .value, with: { (snapshot) in
if let dict = snapshot.value as? [String: Any] else { }
for myModel in self.datasource {
myModel.someValue = dict["someValue"] as? String
}
// I added the gcd timer just to give the loop time to finish just to see if it made a difference
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
self.datasource.sort { return $0.postDate > $1.postDate } // Even though this sorts correctly I also tried commenting this out but no difference
self.collectionView.reloadData()
// I also tried to update the layout
self.collectionView.layoutIfNeeded()
// remove spinner
}
})
}
}
CustomCell Below. This is a much more simplified version of what's inside the myModel property observer. The data that shows in the label is dependent on other data and there are a few conditionals that determine it. Adding all of that inside cellForItem would create a bunch of code that's why I didn't update the data it in there (or add it here) and choose to do it inside the cell instead. But as I said earlier, when I check the data it is always 100% correct. The property observer always works correctly.
CustomCell: UICollectionViewCell {
let imageView: UIImageView = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
let priceLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var someBoolProperty = false
var myModel: MyModel? {
didSet {
someBoolProperty = true
// I read an answer that said try to update the label on the main thread but no difference. I tried with and without the DispatchQueue
DispatchQueue.main.async { [weak self] in
self?.priceLabel.text = myModel.price!
self?.priceLabel.layoutIfNeeded() // tried with and without this
}
let url = URL(string: myModel.urlStr!)
imageView.sd_setImage(with: url!, placeholderImage: UIImage(named: "placeholder"))
// set imageView and priceLabel anchors
addSubview(imageView)
addSubview(priceLabel)
self.layoutIfNeeded() // tried with and without this
}
}
override func prepareForReuse() {
super.prepareForReuse()
// even though Apple recommends not to clean up ui elements in here, I still tried it to no success
priceLabel.text = ""
priceLabel.layoutIfNeeded() // tried with and without this
self.layoutIfNeeded() // tried with and without this
// I also tried removing the label with and without the 3 lines above
for view in self.subviews {
if view.isKind(of: UILabel.self) {
view.removeFromSuperview()
}
}
}
func cleanUpElements() {
priceLabel.text = ""
imageView.image = nil
}
}
I added 1 breakpoint for everywhere I added priceLabel.text = "" (3 total) and once the collectionView reloads the break points always get hit 6 times (3 times for the 2 objects in the datasource).The 1st time in prepareForReuse, the 2nd time in cellForItem, and the 3rd time in cleanUpElements()
Turns out I had to reset a property inside the cell. Even though the cells were being reused and the priceLabel.text was getting cleared, the property was still maintaining it's old bool value. Once I reset it via cellForItem the problem went away.
10 hrs for that, smh
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCell, for: indexPath) as! CustomCell
cell.someBoolProperty = false
cell.priceLabel.text = ""
cell.cleanUpElements()
cell.myModel = dataSource[indexPath.item]
return cell
}
For an app that I'm developing, I'm using a tableview. My tableview, has of course a tableviewcell. In that tableviewcell I'm adding a view programmatically (so nothing in storyboard). It's a view where I draw some lines and text and that becomes a messagebubble. If the messagebubble is seen by the other user you sent it too , a line of the bubble will go open.
So I have the animation function inside the class of that UIView (sendbubble.swift)
Now, it already checks if it is read or not and it opens the right bubble. But normally it should animate (the line that goes open should rotate) in 0.6 seconds. But it animates instantly. So my question is, how do I animate it with a duration?
I would also prefer to still call it in my custom UIView class (sendbubble.swift) . Maybe I need code in my function to check if the cell is presented on my iphone?
Thanks in advance!
func openMessage() {
UIView.animate(withDuration: 0.6, delay: 0.0, options: [], animations: {
var t = CATransform3DIdentity;
t = CATransform3DMakeRotation(CGFloat(3 * Float.pi / 4), 0, 0, 1)
self.moveableLineLayer.transform = t;
}, completion:{(finished:Bool) in })
}
First you need to grab the cell.
Get the indexPath of that cell where you need to show open bubble.
Get the cell from tableView.cellForRowAt(at:indexPath)
We will now have access to that bubble view now you can animate using the same function func openMessage()
Any question? comment.
You need to implement the UITableViewDelegate method tableView(_:willDisplay:forRowAt:) https://developer.apple.com/reference/uikit/uitableviewdelegate/1614883-tableview
That is triggered when the cell is about to be drawn - not when it is created. You will also need to store a state in your model that says if the animation has occurred, otherwise it will happen every time the cell comes back into view.
EXAMPLE
In the view controller (pseudo code)
class CustomViewController: UITableViewDelegate {
//where ever you define your tableview
var tableView:UITableView
tableView.delegate = self
var dataSource //some array that is defining your cells - each object has a property call hasAnimated
func tableView(_ tableView: UITableView, willDisplay cell: ITableViewCell,
forRowAt indexPath: IndexPath) {
if let cell = cell as? CustomTableViewCell, dataSource[indexPath.row].hasAnimated == false {
dataSource[indexPath.row].hasAnimated = true
cell.openMessage()
}
}
}
class CustomTableViewCell: UITableViewCell {
func openMessage() { //your method
}
}
I'm not sure why but my UITapGestureRecognizer is not firing correctly. Well in fact it is not firing at all. I am trying to get a function to run on the tap of an image.
Info about the setup:
Not using storyboards, loading everything programmatically
The view that I am loading this on also has a UICollectionView on it
ok so for the code:
The UIImageView is declared like so:
let backButtonIcon: UIImageView = {
let bbi = UIImageView()
bbi.image = UIImage(named: "backIcon")
bbi.translatesAutoresizingMaskIntoConstraints = false
bbi.layer.zPosition = 2
return bbi
}()
I then added that to the view:
view.addSubview(backButtonIcon)
to add the tap functionality to the UIImageView I am using:
let tapBackButton = UITapGestureRecognizer(target: self, action: #selector(backButtonPressed))
backButtonIcon.isUserInteractionEnabled = true
backButtonIcon.addGestureRecognizer(tapBackButton)
and lastly, here is the function that I am trying to run, just a simple print at the moment:
func backButtonPressed(sender: UITapGestureRecognizer) {
print("Go Back Pressed")
}
Update:
I have already tried adding:
bbi.isUserInteractionEnabled = true
and also:
backButtonIcon.isUserInteractionEnabled = true
Update 2:
I created another blank view and used the code exactly as it is here and it worked.
Could it be something to do with the UICollectionView?
I made the UICollectionView zPosition -1 and the UIImageView zPosition at 1 but that alas that also did not work.
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.
source: https://developer.apple.com/reference/uikit/uiimageview
I think the issue is with the UICollectionView, which is composed of UICollectionViewCells that already have a tap enabled by definition.
I'm looking through a very old app (Swift 1.x) I wrote for my personal usage (as in it never saw the light of day) and here's what I seemed to do - you probably need to do some variation of this:
Subclassed UICollectionViewCell and added a UILabel and UIImageView as subviews to it, populating them (along with a NSURL for the tap action).
Declared (and adopted) a specific UIViewController to also be my UICollectionView delegate (also for my purposes it was a SFSafariViewController delegate).
In that VC's viewDidLoad() I did set up a long press (for removing) and double tap (for reloading) gestures, but did not set up a tap gesture - it isn't needed.
In that VC's viewDidLoad() I loaded (and populated) the cells.
Here's the thing I think you are getting stuck on, but without more code I'm not sure:
Coded against:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? BookmarkCell {
selectedBookmarkSection = indexPath.section
selectedBookmarkRow = indexPath.row
sfc = SFSafariViewController(URL: cell.targetUrl!, entersReaderIfAvailable:true)
sfc.delegate = self
presentViewController(sfc, animated: true, completion: nil)
} else {
// Error indexPath is not on screen: this should never happen.
}
}
Please be kind, as this was something I wrote back in July 2014! (I update the collectionView(didSelectItemAt:indexPath:) for Swift 3.x but that's it.)
TR;DR: I think - particularly if your tap is seen outside of a UICollectionView - that this may get you working.
I have Collection view forming of 3 cells. I am displaying images on them, however, as fetching the image data from the server takes a few seconds, I use nsuserdefaults and cache.
let imagesFromUserDefaults
var dataIsFetched = false
viewDidLoad() {
let imagesFromUserDefaults = // Data from user defaults
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = self.collectionView.dequeueReusableCellWithReuseIdentifier("ACollectionViewCell", forIndexPath: indexPath) as! ACollectionViewCell
let activityView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
activityView.hidesWhenStopped = true
if dataIsFetched == false {
activityView.center = CGPointMake( cell.contentView.frame.size.width / 2, cell.contentView.frame.size.height / 2)
cell.contentView.addSubview(activityView)
activityView.startAnimating()
cell.img = // set image - works
} else {
// Data is fetched from the Server
activityView.stopAnimating()
cell.img = // set image - works
}
func fetchDataFromServer() {
// onSuccessResponse: Store into Array
dataIsFetched = true
collectionView.reloadData()
}
However, after the server data is loaded, even though the images change, the activity indicator doesn't go away. So if cells have the same indexPath.row (as proved by images as well), why doesn't it happen with activity indicator?
Also, is it more logical to place this behaviour to CollectionViewCell class? What is the proper way of handling
Edit:
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if initialLoad {
count = self.defaults.count
} else {
count = self.fetched[0].count
}
print("number of cells \(count)")
if count < 4 {
return count
}
return 0
}
You need to set
let activityView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
activityView.hidesWhenStopped = true
Also you can set activityView.center = cell.center for a cleaner code.
You know, collect view cells are reusable, the 3 cells displayed in the collection view may share the same cell instance. So every time you call the cellForItemAtIndexPath method, you may get the same cell instance, and you repeatedly add an active indicator to the cell but never remove it. That's not good. Imagine what will you to indicate if an image is fetched with YES/NO, that'll be easy, if the image is fetched, you display YES in the cell, otherwise NO. So the indicator is here to do the same thing, the indicator's YES is animating and NO is not animating, don't get tricked because it's spinning, it's not for tracking the whole fetching process. All you need to do is to add the indicator in the prototype cell, and maintain the states of you images, fetched or not. And update the indicator base on the state:
var isImageFetched = yourImagesStates[indexPath.row];
if isImageFetched == true {
cell.indicator.stopAnimating()
cell.img = image
} else {
cell.indicator.startAnimating()
}
hope it'll help.
How to redraw non-visible UICollectionViewCell's ready for when reuse occurs???
One approach I thought of was per the code in the Layout Cell prepareForReuse function, however whilst it works it non-optimal as it causes more re-drawing then required.
Background: Need to trigger drawRect for cells after an orientation change that are not current visible, but pop up to be used and haven't been redraw, so so far I can only see that prepareForReuse would be appropriate. Issue is I'm re-drawing all "reuse" cells, whereas I really only want to redraw those that initially pop up that were created during the previous orientation position of the device.
ADDITIONAL INFO: So currently I'm doing this:
In ViewController:
override func viewWillLayoutSubviews() {
// Clear cached layout attributes (to ensure new positions are calculated)
(self.cal.collectionViewLayout as! GCCalendarLayout).resetCache()
self.cal.collectionViewLayout.invalidateLayout()
// Trigger cells to redraw themselves (to get new widths etc)
for cell in self.cal?.visibleCells() as! [GCCalendarCell] {
cell.setNeedsDisplay()
}
// Not sure how to "setNeedsDisplay" on non visible cells here?
}
In Layout Cell class:
override func prepareForReuse() {
super.prepareForReuse()
// Ensure "drawRect" is called (only way I could see to handle change in orientation
self.setNeedsDisplay()
// ISSUE: It does this also for subsequent "prepareForReuse" after all
// non-visible cells have been re-used and re-drawn, so really
// not optimal
}
Example of what happens without the code in prepareForReuse above. Snapshot taken after an orientation change, and just after scrolling up a little bit:
I think I have it now here:
import UIKit
#IBDesignable class GCCalendarCell: UICollectionViewCell {
var prevBounds : CGRect?
override func layoutSubviews() {
if let prevBounds = prevBounds {
if !( (prevBounds.width == bounds.width) && (prevBounds.height == bounds.height) ) {
self.setNeedsDisplay()
}
}
}
override func drawRect(rect: CGRect) {
// Do Stuff
self.prevBounds = self.bounds
}
}
Noted this check didn't work in "prepareForReuse" as at this time the cell had not had the rotation applied. Seems to work in "layoutSubviews" however.
You can implement some kind of communication between the cells and the view controller holding the collection view ( protocol and delegate or passed block or even direct reference to the VC ). Then You can ask the view controller for rotation changes.
Its a bit messy, but if You have some kind of rotation tracking in Your view controller You can filter the setNeedsDisplay with a simple if statement.
I had similar challenged updating cells that were already displayed and off the screen. While cycling through ALLL cells may not be possible - refreshing / looping through non-visible ones is.
IF this is your use case - then read on. Pre - Warning - if you're adding this sort of code - explain why you're doing it. It's kind of anti pattern - but can help fix that bug and help ship your app albeit adding needless complexity. Don't use this in multiple spots in app.
Any collectionviewcell that's de-initialized (off the screen and being recylced) should be unsubscribed automatically.
Notification Pattern
let kUpdateButtonBarCell = NSNotification.Name("kUpdateButtonBarCell")
class Notificator {
static func fireNotification(notificationName: NSNotification.Name) {
NotificationCenter.default.post(name: notificationName, object: nil)
}
}
extension UICollectionViewCell{
func listenForBackgroundChanges(){
NotificationCenter.default.removeObserver(self, name: kUpdateButtonBarCell, object: nil)
NotificationCenter.default.addObserver(forName:kUpdateButtonBarCell, object: nil, queue: OperationQueue.main, using: { (note) in
print( " contentView: ",self.contentView)
})
}
}
override func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("die", forIndexPath: indexPath) as UICollectionViewCell
cell.listenForBackgroundChanges()
return cell
}
// Where appropriate broadcast notification to hook into all cells past and present
Notificator.fireNotification(notificationName: kUpdateButtonBarCell)
Delegate Pattern
It's possible to simplify this.... an exercise for the reader. just do not retain the cells (use a weak link) - otherwise you'll have memory leaks.