S.Verma
S.Verma

Reputation: 199

How do I put an UIImageView in the center of a tableView

I want my image to be in the center in the x axis, I'm writing this code :

let emptyImage=UIImageView(frame: CGRect(x: (UIScreen.main.bounds.width)/2 ,y: 200 , width: 50, height: 50))

but it doesn't work.

Upvotes: 0

Views: 921

Answers (4)

Venkat057
Venkat057

Reputation: 187

As you are trying to create image in code. Try adding anchors between imageView and tableview. Find below peace of example code.

    let emptyImage = UIImageView(image: UIImage(named: ""))
    view1.backgroundColor = UIColor.black // view1 consider this as your tableview
    emptyImage.translatesAutoresizingMaskIntoConstraints = false //missed it in first place
    self.view1.addSubview(emptyImage)
    NSLayoutConstraint.activate([
            emptyImage.centerXAnchor.constraint(equalTo: view1.centerXAnchor),
            emptyImage.centerYAnchor.constraint(equalTo: view1.centerYAnchor),
            emptyImage.heightAnchor.constraint(equalToConstant: 100),
            emptyImage.widthAnchor.constraint(equalToConstant: 100)
        ])

Hope this helps!

Upvotes: 0

Rauan
Rauan

Reputation: 148

If you want to show an UIImageView instead of cells, then try this:

  let emptyImage=UIImageView(frame: 
                             CGRect(x: 0, 
                                    y: 0, 
                          width:   self.tableView.bounds.size.width,            
                          height: self.tableView.bounds.size.height))

  self.tableView.backgroundView = emptyImage

Upvotes: 0

silentBob
silentBob

Reputation: 170

Try setting imageView center property to tableView.center:

imageView.center = tableView.center

Upvotes: 0

Sagar Bhut
Sagar Bhut

Reputation: 657

try this

let emptyImage = UIImageView(frame: CGRect(x: UIScreen.main.bounds.width/2 - 50/2, y: 200, width: 50, height : 50)

Upvotes: 1

Related Questions