Thanks guys for your solutions!
Looking at them I could cope with this task!
So here it is.
First add a new instance variable:
var dynamicHeight = CGFloat()
Next change the image variable implementation to this:
var image: UIImage? {
didSet {
if let theImage = image {
let aspectRatio = theImage.size.width / theImage.size.height
dynamicHeight = (CGFloat(260) / aspectRatio)
imageView.image = theImage
imageView.isHidden = false
imageView.frame = CGRect(x: 10, y: 10, width: 260, height: dynamicHeight)
addPhotoLabel.isHidden = true
}
}
}
Then in tableView(_ tableView:heightForRowAt indexPath:) change the if statement to:
} else if indexPath.section == 1 {
if imageView.isHidden {
return 44
} else {
return dynamicHeight + 20
}
}
We can’t control the position and size of the image view through the storyboard, and anything you change in the size inspector regarding to the autoresize won’t take effect, as we set the parameters of the view through the code.
And what should we do in the code is to:
- calculate the dynamicHeight;
- set it as the actual height parameter of our imageView’s frame property;
- set the heightForRow of the 1st section 20 points bigger than the dynamicHeight.
UPD1: And after refactoring the code we have:
override func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat {
...
case (1, _):
return imageView.isHidden ? 44 : (dynamicHeight + 20)
...
}
Tried this out even using panorama images — works perfectly!
UPD2: Later in the chapter we’ll actually need the show(image:) method to show the images in the “Edit Locations” screen, so change the function to:
func show(image: UIImage) {
let aspectRatio = image.size.width / image.size.height
dynamicHeight = (CGFloat(260) / aspectRatio)
imageView.image = image
imageView.isHidden = false
imageView.frame = CGRect(x: 10, y: 10, width: 260, height: dynamicHeight)
addPhotoLabel.isHidden = true
}
and the image variable to:
var image: UIImage? {
didSet {
if let theImage = image {
show(image: theImage)
}
}
}