Current coordinates of a tableViewCell swift - swift

fellows!
I'm trying to make an animation of an image in my tableViewCell. My intent is to get an imageView that is in a tableViewCell, add it to exactly the same place in a view, and then use scale animation. Currently, my code looks as below, however, I need to find a cell center point in every period of time (after scrolling too), that I can add image view exactly in the same place. The value of cellRect.origin.y constantly increases, whereas I need it to be exactly center.y point of my tableView cell.
Could you please tell me where my mistake is?
Thank you in advanse!
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
cell.animateImageView = { [weak self]
guard let self = self else { return }
tableView.layoutSubviews()
var cellRect = self.view.convert(tableView.rectForRow(at: indexPath), to: self.tableView)
cellRect.origin.x = UIScreen.main.bounds.midX - (cell.photoImageView.frame.width / 2)
cellRect.origin.y = cellRect.origin.y + (cell.photoImageView.frame.height / 2)
UIView.animate(withDuration: 3) {
} completion: { isFinished in
}
}
}

If I understand you correctly, this is your goal
you tap on a UITableViewCell which has an imageView
You want to create a new image view with the same image in the same position as the image in the cell you tapped
Then from this position you will make this image full screen with animation
You want to do something after the animation has completed
If yes, there here are my thoughts
I feel this line has the first issue:
var cellRect
= self.view.convert(tableView.rectForRow(at: indexPath),
to: self.tableView)
Let's take a look at the convert function in the docs
Converts a rectangle from the receiver’s coordinate system to that of another view.
Parameters
rect
A rectangle specified in the local coordinate system
(bounds) of the receiver.
view
The view that is the target of the conversion operation. If view
is nil, this method instead converts to window base coordinates.
Otherwise, both view and the receiver must belong to the same UIWindow
object.
The receiver here is your cell's image view which you want to recreate so you should not call self.view.convert, it should be cell.photoImageView.convert
The rect parameter is the bounds of your tapped cell's image view and the to parameter is self.view as you want to convert the image view's coordinates in the cell to the coordinates in the main view of the view controller.
Beyond that I am not sure of the purpose of these as you will get the frame from the above function so I removed them but you can add it back if it makes sense to your application.
cellRect.origin.x
= UIScreen.main.bounds.midX - (cell.photoImageView.frame.width / 2)
cellRect.origin.y
= cellRect.origin.y + (cell.photoImageView.frame.height / 2)
So this is how I changed the function:
func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath)
{
// Retrieved the actual cell that was tapped
// same as what you did
let cell
= tableView.cellForRow(at: indexPath) as! TableViewCell
// Here I made a change based on my explanation above
let cellRect =
cell.photoImageView.convert(cell.photoImageView.bounds,
to: view)
// I created a blue view just for demo
let aView = UIView(frame: cellRect)
aView.backgroundColor = .blue
view.addSubview(aView)
}
If you end it here, you will get this result
The blue view added perfectly where we want it
Now to complete the rest with animation is quite simple after we accomplished the tricky part and here is the full function
func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath)
{
// Retrieved the actual cell that was tapped
let cell
= tableView.cellForRow(at: indexPath) as! TableViewCell
// Here I made a change based on my explanation above
let cellRect =
cell.photoImageView.convert(cell.photoImageView.bounds,
to: view)
let animateImageView = UIImageView(frame: cellRect)
animateImageView.image = cell.photoImageView.image
animateImageView.clipsToBounds = true
view.addSubview(animateImageView)
UIView.animate(withDuration: 2.0)
{ [weak self] in
if let strongSelf = self
{
animateImageView.frame = strongSelf.view.bounds
}
} completion: { (success) in
if success
{
// animation completed, do what you want
// like push your VC
}
}
}
The end result I believe is what you want
I hope this helps you get you closer to your desired result

Related

How to resize the imageView?

How do I resize the imageView?
Xcode says initialisation of imageView was never used.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
let city = nicosiaPlaces [indexPath.row]
cell?.textLabel?.text = city
let imageView = CGSize(width: 100, height: 100)
cell?.imageView?.image = UIImage(named: city)
return cell!
}
You just create a new CGSize every time when the method is called, you should change the size in your cell class instead. And if you're using storyboard with AutoLayout, you should change the size in storyboard.
I guess your question has some flaws inside.
Assuming that you need to resize an Imageview I'm posting small Snippet for you.
Never initialize any new component inside func tableView(cellForRowAt:IndexPath)
beacuse every time it is going to create a new Instance until they are properly disposed.
You have taken reference as let imageView = CGSize(--,--) but you are again calling the instance from Cell Method.
Don't do that.
override func awakeFromNib(){
let imageView = UIImageView(CGRectMake(0,0,150,150))
imageView.contentMode = .scaleAspectFill
contentView.addSubView(imageView)
}
Now In the Class method get reference of the ImageView and resize if you want.
overrride func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.deququeResuableCell(withIdentifier: "cellID",forIndexPath: indexPath) as! yourCustomCellClassName
cell.imageView?.image = UIImage(named: "yourImage")
// If you need to resize the Image make changes in Frame of Image or ContentMode of the Image.
return cell
}

Collection View Cell subview frame not available until cell is reused

I have collection view cells that contain a subview of which I am trying to get the frame of in relation to the superview.
So far, I've managed to successfully get the frame of the subview, however for the first x amount of visible cells, the returned frame is always (0,0,0,0).
After I scroll them out of view and scroll back to those x cells, the returned frame is fine and the frames for the subviews are computed properly.
Any thoughts?
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let window = UIApplication.shared.keyWindow
let selectedCell = self.collectionView(self.cellCollectionView, cellForItemAt: indexPath) as! postCell
let photoItem = selectedCell.photo
let photoItemPosition = photoItem.frame
let convertedFrame = selectedCell.convert(photoItemPosition, to: window)
print(photoItemPosition)
print(convertedFrame)
}
You have to update the frame of photo instance in layoutSubviews.
Override the layoutSubviews in your collectionView cell class
override func layoutSubviews ()
{
super.layoutSubviews()
//Set the self.photo frame
}

adding Button in last tableView Cell shown twice when scrolling

Using Swift4, iOS11.2.1, Xcode9.2,
I successfully added a custom button to the last cell of a tableView. (the button is used to add cells in the tableView - this also works fine...) - see Screenshot-1.
But now the issue: When adding more cells (i.e. more than fit in the tableView-height), and if you scroll to the top, then there is a second cell that shows this button - see Screenshot-2.
(see code below....)
Here are the two screenshots:
How can I get rid of the extra button ????
(it seems that a cell is reused and the button is partly drawn. The cut-off can be explained since the height of the last cell is made bigger than the other cells. But still, there shouldn't be parts of buttons in any other cell than the very last one...even when scrolling up).
Any help appreciated !
Here is my code (or excerts of it...):
override func viewDidLoad() {
super.viewDidLoad()
// define delegates
self.fromToTableView.dataSource = self
self.fromToTableView.delegate = self
// define cell look and feel
self.addButton.setImage(UIImage(named: "addButton"), for: .normal)
self.addButton.addTarget(self, action: #selector(plusButtonAction), for: .touchUpInside)
//...
self.fromToTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let resItems = resItems else {
self.rowCount = 0
return 0
}
self.rowCount = resItems.count - 1
return resItems.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if(indexPath.row == (self.rowCount)) {
return 160
} else {
return 120
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = fromToTableView.dequeueReusableCell(withIdentifier: "SettingsCell") as? SettingsCustomTableViewCell
// configure the cell
cell?.configureCell(tag: indexPath.row)
// fill cell-data
if let resItem = self.resItems?[indexPath.row] {
cell?.connectionItem = resItem
}
// add addButton to last cell
if(indexPath.row == (self.rowCount)) {
// add addButton
cell?.contentView.addSubview(self.addButton)
// scroll to last cell (that was just added)
// First figure out how many sections there are
let lastSectionIndex = self.fromToTableView.numberOfSections - 1
// Then grab the number of rows in the last section
let lastRowIndex = self.fromToTableView.numberOfRows(inSection: lastSectionIndex) - 1
// Now just construct the index path
let pathToLastRow = IndexPath(row: lastRowIndex, section: lastSectionIndex)
// Scroll to last cell
self.fromToTableView.scrollToRow(at: pathToLastRow as IndexPath, at: UITableViewScrollPosition.none, animated: true)
}
return cell!
}
You already figured out what the problem is :)
As you say here:
it seems that a cell is reused and the button is partly drawn
And that is exactly what happens here. You have a pool of UITableViewCell elements, or in your case SettingsCustomTableViewCell. So whenever you say:
let cell = fromToTableView.dequeueReusableCell(withIdentifier: "SettingsCell") as? SettingsCustomTableViewCell
Then, as the name implies, you dequeue a reusable cell from your UITableView.
That also means that whatever you may have set on the cell previously (like your button for instance) stays there whenever you reuse that specific instance of a cell.
You can fix this in (at least) three ways.
The Hack
In your tableView(_:cellForRowAt:indexPath:) you have this:
if(indexPath.row == (self.rowCount)) {
//last row, add plus button
}
You can add an else part and remove the plus button again:
if(indexPath.row == (self.rowCount)) {
//last row, add plus button
} else {
//not last row, remove button
}
The Right Way
UITableViewCell has the function prepareForReuse and as the documentation says:
If a UITableViewCell object is reusable—that is, it has a reuse identifier—this method is invoked just before the object is returned from the UITableView method dequeueReusableCell(withIdentifier:)
So, this is where you "reset" your custom table view cell. In your case you remove the plus button.
You already have a custom UITableViewCell it seems, so this should be a small change.
The Footer Way
As #paragon suggests in his comment, you can create a UIView and add that as a tableFooterView to your UITableView.
let footerView = YourFooterViewHere()
tableView.tableFooterView = footerView
Hope that helps

tableViewCell image property reset when selected - swift

I do create a custom cell with 2 UIImageView inside and a UILabel this way:
let ChildCellID = "ChildCell"
if indexPath.section < 2 {
var cell = SectionCell.loadOrDequeueWithTableView(tableView, reuseIdentifier: SectionCellID)
if cell == nil {
cell = SectionCell.viewFromNib()
}
cell.delegate = self as SectionCellDelegate
cell.avatar?.loadAvatarURL(child.avatarUrl)
cell.avatar.layer.cornerRadius = cell.avatar.frame.size.width / 2
The attribut avatar is the UIImageView I decided to round. When a cell is selected my code goes:
func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
let tableViewCell = tableView.cellForRowAtIndexPath(indexPath)
if let cell : SectionCell = tableViewCell as? SectionCell {
cell.selection = !cell.selection
} else if let cell : ChildCell = tableViewCell as? ChildCell {
cell.selection = !cell.selection
}
return indexPath
}
Selection is the checkbox as UIImageView. My problem is when I select a cell, the cell.avatar loses his property meaning it goes back as a square form. The cell.avatar is still loaded and I tried cell.avatar.layer.cornerRadius = cell.avatar.frame.size.width / 2in the willSelectRowAtIndexPath and didSelectRowAtIndexPath but without success.
Am I missing anything that makes my avatar loses his rounded property ?
The only thing that could possibly be the origin of this problem would be the fact that I do use the checkbox UIImageView which is really near my avatar.
I found out that the checkbox near my avatar lacked a constraints that, for some random reason and even though it did not impact the avatar view, was resetting the avatar view rounded property.

UICollectionView Not Updated with custom UIViewController

I created a custom UIViewController and extended it to implement: UICollectionViewDataSource, UICollectionViewDelegate. In story board, I added UICollectionView and made reference from my controller to this UICollectionView (and setup the delegates for data source and collection view delegate).
I obviously implemented the minimal requirements for these 2 delegates. Now, since i sometimes asynchronously load images, I call cell.setNeedsLayout(), cell.layoutIfNeeded(), cell.setNeedsDisplay() methods after image download done (cell.imageView.image = UIImage(...)). I know all these methods are called. However, the images on the screen were not updated.
Did I miss something? Thank you!
Edit: Add Sample code - how update was called -
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
....
let cellImage = ServiceFacade.sharedInstance.getImageFromCaching(image!.url)
if cellImage == nil {
// set image to default image.
cell.cellImage.image = UIImage(named: "dummy")
ServiceFacade.sharedInstance.getImage(image!.url, completion: { (dImage, dError) in
if dError != nil {
...
}
else if dImage != nil {
dispatch_async(dispatch_get_main_queue(),{
let thisCell = self.collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell
thisCell.cellImage.image = dImage
thisCell.setNeedsLayout()
thisCell.setNeedsDisplay()
thisCell.layoutIfNeeded()
})
}
else{
// do nothing
}
})
}
else {
cell.cellImage.image = cellImage!
cell.setNeedsDisplay()
}
// Configure the cell
return cell
}
Chances are the UICollectionView has cached an intermediate representation of your cell so that it can scroll quickly.
The routine you should be calling to indicate that your cell needs to be updated, resized, and have it's visual representation redone is reloadItemsAtIndexPaths with a single index path representing your cell.