1

When I use the StoryBoard, I can add an UIImageView to UITableView like this:

enter image description here

I am trying to write an UIScrollView extension to add a parallax image into a UITableView which can be reused for all the tables easily. Here my code to add image:

 extension UIScrollView {

  func addParallaxImage(image image: UIImage, height: CGFloat) {
    let myImageView: UIImageView = UIImageView()
    myImageView.image = image
    myImageView.contentMode = UIViewContentMode.ScaleAspectFill

    myImageView.frame.size.width = UIScreen.mainScreen().bounds.size.width
    myImageView.frame.size.height = height
    myImageView.frame.origin.y = 0

    self.addSubview(myImageView)

  }

}

Function usage:

tableView.addParallaxImage(image: UIImage(named: "pets")!, height: 100)

However, my image overlaps the table.

enter image description here

Any solutions?

AnLT
  • 569
  • 8
  • 22

3 Answers3

1

The best solution for your case is used tableview header and here the most usable libs:-

CSStickyHeaderFlowLayout

ParallaxTableViewHeader

VGParallaxHeader

APParallaxHeader

Take care not all libs support Swift, I hope I help you.

Ahmed Abdallah
  • 2,338
  • 1
  • 19
  • 30
0

If you wanna reused the cell. You can try to add the ImageView into your tableViewCell. By the way, the header and the footer can be reused too.

Ws_
  • 24
  • 6
  • I am sorry, I don't want to reuse cell. I am using reuse cell now. However, I want to improve it. – AnLT Jul 26 '16 at 08:58
  • Try to make tableView contentInset . `tableView.contentInset = UIEdgeInsetsMake(top, left, bottom, right)` – Ws_ Jul 26 '16 at 09:05
  • If you want the Image behind the table, you should add ImageView to the superView first . – Ws_ Jul 26 '16 at 09:08
  • I create my table by drag an UITableView into Xib file. I just want to impact the table by code in extension. Is it possible? – AnLT Jul 26 '16 at 09:12
0

Instead of addSubview try using insertSubview(_ view: UIView, atIndex index: Int) with index 0, so it won't be above your cells.

johnyu
  • 2,152
  • 1
  • 15
  • 33
  • It only make my image under the table. It means you can see the image, coz the table will overlap it. :( – AnLT Jul 26 '16 at 09:11
  • If you don't want them to overlap, you'll have to put the picture in tableView header, so it's not possible as an extension on scroll view. – johnyu Jul 26 '16 at 09:28
  • As I mentioned above, I want something like Storyboard way. :3 – AnLT Jul 26 '16 at 09:31
  • 1
    Storyboard way is to use table view header, so that would be exactly like storyboard way. – johnyu Jul 26 '16 at 09:42