How to add image with parallax effect above UITableView header and keep header sticky?

NSPratik picture NSPratik · Jun 17, 2015 · Viewed 19k times · Source

Here is an image that explains everything I want to do:

enter image description here

My question is, how would I make my view structure. The header of the table view should be fixed at top of the table. But what about the top most image that is above the table view header. Will I have to add the table view inside the UIScrollView ?

Parallax effect can be done by CATransform3D, but how would I achieve what I want, that is my question. There are lots of demos but I want to make it done custom.

Answer

JAINESH DOSHI picture JAINESH DOSHI · May 14, 2018

You can add image view to the view like -

let imageView = UIImageView()
let lblName = UILabel()

imageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 300)
imageView.image = UIImage.init(named: "poster")
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
view.addSubview(imageView)

lblName.frame = CGRect(x: 20, y: 100, width: 200, height: 22)
lblName.text = "Steve Jobs"
lblName.textColor = UIColor.white
lblName.font = UIFont.systemFont(ofSize: 26)
lblName.clipsToBounds = true
imageView.addSubview(lblName)

After that in tableview delegate method you can add scrollviewDidScroll method like -

let y = 300 - (scrollView.contentOffset.y + 300)
let height = min(max(y, 60), 400)
imageView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: height)
lblName.frame = CGRect(x: 20, y: height - 30, width: 200, height: 22)

I hope this will be helpful. Please correct me if I am wrong.

enter image description here