You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中关联随机图片生成器与第二个视图控制器及崩溃修复

问题解决步骤

1. 修复数组越界崩溃,实现图片耗尽时跳转

修改主ViewController的randomButtonPressed方法,先检查当前索引是否在数组范围内,超出时执行页面跳转:

@IBAction func randomButtonPressed(_ sender: UIButton) {
    // 检查是否还有未显示的图片
    guard imageMain < array.count else {
        // 图片耗尽,跳转到重置页面
        performSegue(withIdentifier: "goToResetVC", sender: self)
        return
    }
    
    mainImageView.image = array[imageMain]
    imageMain += 1
}

注意:需要在Storyboard中给主VC到第二个VC的segue设置标识符为goToResetVC;如果用代码跳转,可替换为present(ResetViewController(), animated: true)。

2. 配置重置页面(ResetViewController)

在已创建的第二个ViewController中,给重置按钮添加点击事件,实现返回主页面的逻辑:

import UIKit

class ResetViewController: UIViewController {
    @IBAction func resetButtonPressed(_ sender: UIButton) {
        // 关闭当前页面回到主VC
        dismiss(animated: true)
    }
}

3. 主VC返回后重置状态并重新洗牌

在主ViewController中重写viewWillAppear方法,每次回到主页面时自动重置索引、洗牌数组并恢复初始图片:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // 重新洗牌图片数组
    array.shuffle()
    // 重置图片索引
    imageMain = 0
    // 恢复初始显示图片
    mainImageView.image = #imageLiteral(resourceName: "start-image")
}

完整修改后的主VC代码

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var mainImageView: UIImageView!
    
    var imageMain = 0
    var array = [ #imageLiteral(resourceName: "raven-988218_1280"), #imageLiteral(resourceName: "halloween-2905531_1280"), #imageLiteral(resourceName: "bird-skull-4433244_1280"), #imageLiteral(resourceName: "candles-1868640_1280"), #imageLiteral(resourceName: "tombstone-2542946_1280"), #imageLiteral(resourceName: "fantasy-2847724_1280") ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        mainImageView.image = #imageLiteral(resourceName: "start-image")
        array.shuffle()        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        array.shuffle()
        imageMain = 0
        mainImageView.image = #imageLiteral(resourceName: "start-image")
    }
    
    @IBAction func randomButtonPressed(_ sender: UIButton) {
        guard imageMain < array.count else {
            performSegue(withIdentifier: "goToResetVC", sender: self)
            return
        }
        
        mainImageView.image = array[imageMain]
        imageMain += 1
    }
}

内容的提问来源于stack exchange,提问作者TheOtisLegion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:42:59