gpt4 book ai didi

ios - 从数组中动态添加 UIImageView

转载 作者:行者123 更新时间:2023-11-30 14:09:47 30 4
gpt4 key购买 nike

我想动态地将 UIImageViews 数组添加到 View 中。当我迭代 for 循环时,似乎只添加了最后一个 UIImageView,而不是数组中的所有内容:

// same image to be used 
let imageName = "img.png"
let image = UIImage(named: imageName)

// array of UIImageViews
var images : [UIImageView?] = Array(count: 10, repeatedValue: UIImageView(image: image))

// iterate and add to view
for i in 0...9 {

// setup UIImageView
// this is how I know only the last UIImageView is added to the parent view
// the y cordinate is about 10 points down (this is expected of i+i array size with of 10)

images[i]?.frame = CGRect(x: 10, y: CGFloat(i+i), width: image!.size.width, height: image!.size.height)

// add to parent view
parentView.addSubview(images[i]!)

}

有没有简单的解决办法?我感觉好像我错过了一些明显的东西。

最佳答案

因为您使用的是Array(count: 10,repeatedValue: UIImageView(image: image))repeatedValue表示您要添加到此的所有 ImageView 数组引用同一个对象。这样一来,你就只有一个imageview,怎么可能添加那么多副本呢。检查我的答案。 enter image description here

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let myWidth = 40
let myHeight = 40

// same image to be used
let imageName = "img.png"
let image = UIImage(named: imageName)

// iterate and add to view
for i in 0...9 {
var imageView: UIImageView = UIImageView(image: image)
imageView.frame = CGRect(x: 10, y: myHeight * i, width: myWidth, height: myHeight)

// add to parent view
self.view.addSubview(imageView)

}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

关于ios - 从数组中动态添加 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31888732/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com