简体   繁体   中英

How to create UIImageVIew in custom UITableViewCell? (Swift)

I have a UITableView in a UIViewController , and 1 prototype cell which is defined in my own custom cell class. I have a UIImageView in the top right corner, with top and trailing margin constraints, as well as a fixed width and height:

In Interface Builder

The problem is, when I run the program, the TableView is created but the imageView is oversized:

At runtime

After researching some similar questions on this site, I've come to the conclusion that:

The cell's imageView only appears and is sized when you assign an image to it.

I've already tried the following code in the custom cell class, and the cellForRowAtIndexPath function:

cell.imageView?.frame = CGRectMake(300, 52, 292, 136)
cell.imageView?.clipsToBounds = true
cell.contentView.addSubview(cell.imageView!)

Am I missing something or what do I do to get the imageView to the size I've made its constraints for?

Thank you in advance!

UIView具有contentMode属性-尝试将其定义为ScaleToFill:

self.someImage.contentMode = .ScaleToFill 

Thanks for the help everyone!

I made a stupid mistake by referencing the custom cell's generic imageView? , rather than the IB Outlet I made under a different name.

Wrong:

cell.imageView?.image = UIImage(named: "whatever name")

Right:

cell.dogImageView.image = UIImage(named: "labrador")

Out of interest, what values are the fixed width and height constraints? It's hard to tell the difference between the interface builder and the device screenshots as the size of the view controller is different.

My suggestion would be doing away with the fixed width and height constraints, and instead:

• Pin the bottom of the image view to the bottom of the cell - this gives the image view it's height.

• Add an aspect ratio constraint to the image view - this gives the image view it's width, based on it's height.

This means that even if you end up changing the height of your cells, your image view will always fit inside of the cell.

Kudos for using prototype cells and a UITableViewCell subclass though - I agree with this method completely!

Your code seems vague although I agree with you using the custom cell class. What this does is to attempt to download all images set and if unable to download, it will replace the image with an image placeholder saved on the assets. All images have the same sizes when loaded.

Here is what you can do to make it work. Here is your custom class.

class SomeCell: UITableViewCell {

    @IBOutlet weak var imgMain: UIImageView!
    @IBOutlet weak var lblMain: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        imgMain.layer.cornerRadius = 5.0
        imgMain.clipsToBounds = true
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func configureCell(image: UIImage, text: String){
        imgMain.image = image
        lblMain.text = text
    }

}

Then on your ViewController

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var somePics = ["http://www.something.com/pic1.jpg","http://www.something.net/pic2.jpg","http://www.something.com/pic3.jpg","http://www.something.com/pic4.jpg","http://www.something.net/pic5.jpg"]

    var someTitles = ["Picture 1", "Picture 2", "Picture 3", "Picture 4", "Picture 5"]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        // Do any additional setup after loading the view, typically from a nib.
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCellWithIdentifier("SomeCell") as? SomeCell {

            var img: UIImage!

            let url = NSURL(string: somePics[indexPath.row])!

            if let data = NSData(contentsOfURL: url) {
                img = UIImage(data: data)
            }else {
                img = UIImage(named: "somePlaceholderpic")
            }

            cell.configureCell(img, text: someTitles[indexPath.row])

            return cell

        } else {

            return SomeCell()

        }
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return somePics.count
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Hope this helps. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM