Moondra
Moondra

Reputation: 4511

Have UIimageView width of custom TableViewCell be 1/3 of cell width, and height of cell = image aspect ratio

I'm new to iOS programming, and I'm mainly been using the interface builder to adjust cell layouts. Currently I have a custom TableView cell with an ImageView and Label.

I would like to:

1) Have the ImageView Width = 1/3 size of cell ( It doesn't seem like I can do this via storyboard)

2) Have the cell height dynamically adjust as the aspect ratio of image is maintained. I've already added constraints for the UIImageView to equal cell height.

I searched StackOverflow but some of the answers got really complicated, so I couldn't really understand how to fit it to my case. I played around with constraints, but it seems I have to do this programmatically?

Here is what I currently have for cell methods:

extension FirstTableViewController: UITableViewDelegate, UITableViewDataSource{

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let folderCell = dataCells[indexPath.row]
        print(folderCell)
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FirstTableViewCell
        cell.setCell(cell:folderCell)
        return cell

Here is my cell class:

class FirstTableViewCell: UITableViewCell {


    @IBOutlet weak var ImageView: ScaledHeightImageView!
    @IBOutlet weak var FolderLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        //print(FolderLabel)


    }
    func setCell (cell : FolderCell){
        self.ImageView.image = cell.image
        self.FolderLabel.text = cell.label
    }
}

Upvotes: 0

Views: 266

Answers (1)

Mohamed Mostafa
Mohamed Mostafa

Reputation: 1057

You can do it from storyboard by adding equal width with superview, then change it's Multiplier to be 0.3enter image description here

enter image description here

Upvotes: 2

Related Questions