【发布时间】:2018-06-17 11:51:46
【问题描述】:
我试图在UICollectionViewCell 中获取UIImageView 的帧大小。我目前尝试使用thumbnailImageView.frame.size 来实现这一点,但无论我从哪里调用此方法,它都会返回(0.0, 0.0)。
我想这样做的原因是在图像视图中对图像的边缘进行圆角处理,但由于我使用的是.scaleAspectFit,因此我需要知道帧大小和图像大小才能正确圆角。
下面是单元格类:
class SomeCollectionViewCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let thumbnailImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
return imageView
}()
private func setLabel(label: UILabel, textSize: CGFloat = 15.0, textColour: UIColor = UIColor.black) -> UILabel {
label.textColor = textColour
label.textAlignment = .center
label.font = label.font.withSize(textSize)
return label
}
var firstLabel: UILabel = UILabel()
var secondLabel: UILabel = UILabel()
var thirdLabel: UILabel = UILabel()
func setupViews() {
firstLabel = setLabel(label: firstLabel)
secondLabel = setLabel(label: secondLabel)
thirdLabel = setLabel(label: thirdLabel)
addSubview(thumbnailImageView)
addSubview(firstLabel)
addSubview(secondLabel)
addSubview(thirdLabel)
addConstraintWithFormat(format: "V:|-25-[v0(125)]-[v1(16)]-[v2(16)]-[v3(17)]-25-|", views: thumbnailImageView, firstLabel, secondLabel, thirdLabel)
addConstraintWithFormat(format: "H:|[v0]|", views: thumbnailImageView)
addConstraintWithFormat(format: "H:|[v0]|", views: firstLabel)
addConstraintWithFormat(format: "H:|[v0]|", views: secondLabel)
addConstraintWithFormat(format: "H:|[v0]|", views: thirdLabel)
}
}
extension UIView {
func addConstraintWithFormat(format: String, views: UIView...) -> Void {
var viewDictionary = [String : UIView]()
for (index, view) in views.enumerated() {
let key = "v\(index)"
viewDictionary[key] = view
view.translatesAutoresizingMaskIntoConstraints = false
}
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewDictionary))
}
}
【问题讨论】:
-
让 imageViewSize = cell.yourImageView.frame.size
-
@ElTomato 我试过了,它仍然返回 (0.0, 0.0)。
-
那么要么你的 IBOutlet 对象没有连接,要么你没有讲述整个故事。
-
我没有使用情节提要。图像在集合视图中正确显示。
-
尝试在layoutSubviews()中获取frame
标签: swift uicollectionview uiimageview uicollectionviewcell