从一个数组中创建一个在一行中显示多个UIImageViews的类可以通过以下步骤实现:
以下是一个示例代码:
import UIKit
class ImageRowView: UIView {
func createImageViews(from images: [UIImage]) {
for image in images {
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(imageView)
// 设置图片视图的约束
NSLayoutConstraint.activate([
imageView.topAnchor.constraint(equalTo: topAnchor),
imageView.bottomAnchor.constraint(equalTo: bottomAnchor),
imageView.leadingAnchor.constraint(equalTo: leadingAnchor),
imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: 1.0)
])
}
}
}
使用示例:
let images = [UIImage(named: "image1"), UIImage(named: "image2"), UIImage(named: "image3")]
let imageRowView = ImageRowView(frame: CGRect(x: 0, y: 0, width: 300, height: 100))
imageRowView.createImageViews(from: images)
// 将自定义视图添加到父视图中显示
parentView.addSubview(imageRowView)
这样,你就可以通过传入一个包含多个UIImage对象的数组,创建并显示多个UIImageViews,并且它们会在一行中水平排列显示。
领取专属 10元无门槛券
手把手带您无忧上云