我制作了一个scrollview,并制作了一个图像数组(我稍后会为用户添加一个选项,将图像发布到该数组中,并且朋友图像将填充到该数组中)并希望用户能够看到一张照片并跟踪它。
我创建了一个for循环,将照片添加到数组中,但是当我创建一个if语句来取出数组中的一个项目时,我收到一个错误,因为我会从数组中删除图像[i]而我有点知道为什么会这样,但想要解决它。所以基本上我需要在阵列中取出一个图像。
请帮助我,我还在学习。
class ViewController: UIViewController {
var imageArray = [UIImage]()
@IBOutlet weak var mainScrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
mainScrollView.frame = view.frame
imageArray = [#imageLiteral(resourceName: "dubai6"), #imageLiteral(resourceName: "dubai2"), #imageLiteral(resourceName: "dubai7"), #imageLiteral(resourceName: "dubai4"), #imageLiteral(resourceName: "dubai3"), #imageLiteral(resourceName: "dubai5"), #imageLiteral(resourceName: "DigitalDrawingPreview"), #imageLiteral(resourceName: "denarus"), #imageLiteral(resourceName: "dubai1")]
for i in 0..<imageArray.count {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.image = imageArray[i]
let xPosition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: self.view.frame.width, height: self.mainScrollView.frame.height)
mainScrollView.contentSize.width = mainScrollView.frame.width * CGFloat(i + 1)
mainScrollView.addSubview(imageView)
}
for i in 0..<imageArray.count {
if (i >= 2) {
imageArray.remove(at: (i - 2))
}
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
谢谢你们更好的程序员。
答案 0 :(得分:0)
在遍历数组时,无法从数组中删除元素,因此必须使用临时数组
class ViewController: UIViewController {
var imageArray = [UIImage]()
@IBOutlet weak var mainScrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
mainScrollView.frame = view.frame
imageArray = [#imageLiteral(resourceName: "dubai6"), #imageLiteral(resourceName: "dubai2"), #imageLiteral(resourceName: "dubai7"), #imageLiteral(resourceName: "dubai4"), #imageLiteral(resourceName: "dubai3"), #imageLiteral(resourceName: "dubai5"), #imageLiteral(resourceName: "DigitalDrawingPreview"), #imageLiteral(resourceName: "denarus"), #imageLiteral(resourceName: "dubai1")]
for i in 0..<imageArray.count {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.image = imageArray[i]
let xPosition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: self.view.frame.width, height: self.mainScrollView.frame.height)
mainScrollView.contentSize.width = mainScrollView.frame.width * CGFloat(i + 1)
mainScrollView.addSubview(imageView)
}
let tempArr = imageArray
for i in 0..<tempArr.count {
if (i >= 2) { // Breakpoint here
imageArray.remove(at: (i - 2))
}
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
使用step over遍历for循环的每一行,直到它崩溃,然后将光标悬停在它上面打印i的值或在控制台po i
输入命令并输入