我在主视图控制器中有一个集合视图。我想将图像随机加载到集合视图单元中。问题是在情节提要中向图像添加上下约束之后,我无法在代码中设置图像在单元格中的位置。
我的代码:
class HomeViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
// disable auto layout
collectionView.translatesAutoresizingMaskIntoConstraints = false
}
}
extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionViewCell", for: indexPath) as! HomeCollectionViewCell
cell.nameLabel.text = names[indexPath.item]
cell.avatarImage.image = avatarImages[indexPath.item]
cell.updateView()
return cell
}
}
class HomeCollectionViewCell: UICollectionViewCell {
func updateView() {
let height = self.frame.height
let width = self.frame.width
// testing if the image changed origin position on load
self.avatarImage.frame.origin.x = width / 2 - self.avatarImage.bounds.width / 2 //xpos
self.avatarImage.frame.origin.y = height / 2 - self.avatarImage.bounds.height / 2 //ypos
// random position image
}
}
我尝试将autoResizing设置为false。图像没有移动。如果我像UIImageView can't change position programmatically这样将约束作为IBOutlet连接到HomeVC,那么我将不知道如何将该信息传递到单元格。任何帮助表示赞赏!