Home > Enterprise >  How to make optional images in a UITableViewCell?
How to make optional images in a UITableViewCell?

Time:01-24

Hi I'm making an app with UIkit and I'm having a problem trying to achieve the layout of a cell.

What I want is to make a cell that has an image header, a stack of user images, and a label. I place this cell in a UITableView. The problem I'm having is that the image header is optional so if it's not there I need it to display like the cell shown below in the attached image.

image

Can someone who has more knowledge in UIkit help me please?

CodePudding user response:

let suppose you have struct that use to populate tableview

struct User {
  let name:String
  let headerImage:UIImage? // an optional image
}

your controller

class ViewController:UIViewController {
  var users = [User]()


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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      if let image = users[indexPath.row].image {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserHeaderCell", for: indexPath) as! UserHeaderCell
        return cell
      } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserSimpleCell", for: indexPath) as! UserSimpleCell
        return cell
      }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       if let image = users[indexPath.row].image {
        return 100 // with image
       }
        return 50 // without image
    }


}

make two cell one for header image and one for simple

class UserHeaderCell:UITableViewCell {


}

class UserSimpleCell:UITableViewCell {


}
  • Related