问题
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:
- Add a custom class for this custom tableViewCell.
- Create a custom tableViewCell inside the tableView through the storyboard.
- Add image inside this custom tableViewCell.
- 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