我一直在尝试(以编程方式)将元素的大小和位置固定到tableviewcell上,以便它们应该自动调整大小并在所有设备上看起来都不错。这是我在自定义单元格的XIB文件中一直使用的代码,但不会自动调整大小。 在使用表格视图中的单元格的viewcontroller中,我声明要以这种方式成为行的高度:
collectionViewImages.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height * 0.27)
self.tableViewDishes.dataSource = self
self.tableViewDishes.delegate = self
self.tableViewDishes.rowHeight = self.view.frame.height * 0.1678
... Xib文件:
@IBOutlet weak var dishImage: UIImageView!
@IBOutlet weak var dishName: UILabel!
@IBOutlet weak var dishDescription: UITextView!
@IBOutlet weak var dishPrice: UILabel!
@IBOutlet weak var addDishButton: UIButton!
@IBOutlet weak var removeDishButton: UIButton!
@IBOutlet weak var dishQuantity: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let width = contentView.frame.width
let height = contentView.frame.height
//MISSING SIZE ADJUSTING FOR THE TEXTS, IGNORE
//Sets the image position of the cells
dishImage.center.x = width * 0.1739
dishImage.center.y = height * 0.4933
dishImage.frame.size = CGSize(width: width * 128/414, height: height * 128/150)
dishImage.layer.cornerRadius = height * 0.1
//Sets the quantity label
dishQuantity.center.x = width * 374.5/414
dishQuantity.center.y = height * 31.5/150
//Sets the position of the title and text
dishName.frame = CGRect(x: width * 156/414, y: height * 21/150, width: width * 241/414, height: height * 20/150)
//Sets position of description and description text
dishDescription.frame = CGRect(x: width * 156/414, y: height * 49/150, width: width * 190/414, height: height * 59/150)
//Sets position and text of price label
dishPrice.frame = CGRect(x: width * 156/414, y: height * 117/150, width: width * 190/414, height: height * 21/150)
//Sets position of addDishButton
addDishButton.frame = CGRect(x: width * 363/414, y: height * 67/150, width: width * 22/414, height: height * 22/150)
//Sets position of removeDishButton
removeDishButton.frame = CGRect(x: width * 363/414, y: height * 97/150, width: width * 22/414, height: height * 22/150)
}