How add Size and Position to ImageView in UITableView Cell?

拜拜、爱过 提交于 2019-12-25 02:44:34

问题


I added a image to my UITableView Cell:

cell.imageView!.image = UIImage(named: "Default.png")

Everything works, the image is displayed. Now I want to give a custom size and position for the image, so I try it with this code:

cell.imageView!.frame = CGRect(x: 29, y: 17, width: 14, height: 13)

But for any reason it doesn't work. Any advices?


回答1:


If your position will not change You can create frame in your TableViewCell

class TableViewCell: UITableViewCell {

@IBOutlet weak var imageView: UIImageView!

override func layoutSubviews() {
    super.layoutSubviews()

    self.imageView?.frame = CGRect(x: 12, y: 23, width: 12, height: 100)
}
}

You can change frame in tableview(cellForRowAt) but If frame will not change its a bad because cellForRowAt run when scrolling up - down or loading cell . You can define in UITableViewCell once.




回答2:


  1. Add a custom class for this custom tableViewCell.
  2. Create a custom tableViewCell inside the tableView through the storyboard.
  3. Add image inside this custom tableViewCell.
  4. Add constraints (top, bottom, leading, trailing) to this image.

This way, you won't have to do anything programmatically and the image size issues will be taken care of by these constraints.




回答3:


  • It'd be better if you do that frame related things in storyboard or Xib files itself. if you want them with static frame.

RunTime:

  • You can use NSLayoutConstraints
  • You can change the frame in draw(_ rect: CGRect) method.


来源:https://stackoverflow.com/questions/54670429/how-add-size-and-position-to-imageview-in-uitableview-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!