如何在 @IBAction 中调用一组 URL?

How can I call an array of URLs in an @IBAction?

swift 的新手 - 缓慢但肯定地开始完全理解这一点。

我将如何在 @IBAction 中调用结构化的 URL 数组 weeks.urls[0]?我附上了错误的屏幕截图,以及我的 WeekDetalViewController 代码。


class WeekDetailViewController: UIViewController {

    var week: WeekInfo!


    @IBOutlet weak var lessonCompleteBtn: UIButton!
    @IBOutlet weak var Button1: UIButton!
    @IBOutlet weak var Button2: UIButton!
    @IBOutlet weak var Button3: UIButton!
    @IBOutlet weak var Button4: UIButton!


    override func viewDidLoad() {
        super.viewDidLoad()


        lessonCompleteBtn.backgroundColor = UIColor.gray
        lessonCompleteBtn.layer.cornerRadius = 20

    }
    @IBAction func lessonBtnTapped(_ sender: AnyObject) {
        sender.setTitle("PSET Complete!", for: [])
        if lessonCompleteBtn.backgroundColor == UIColor.gray{
            lessonCompleteBtn.backgroundColor = UIColor(red: 17/255, green: 107/255, blue: 0/255, alpha: 1.0)
        }
        else if lessonCompleteBtn.backgroundColor == UIColor(red: 17/255, green: 107/255, blue: 0/255, alpha: 1.0){
            sender.setTitle("Complete PSET!", for: [])
            lessonCompleteBtn.backgroundColor = UIColor.gray
        }
    }

    @IBAction func Button1(_ sender: Any) {
        UIApplication.shared.open(URL(week.urls[0])!)

    }
    @IBAction func Button2(_ sender: Any) {
        UIApplication.shared.open(URL(week.urls[1])!)
    }
    @IBAction func Button3(_ sender: Any) {
        UIApplication.shared.open(URL(week.urls[2])!)
    }
    @IBAction func Button4(_ sender: Any) {
       UIApplication.shared.open(URL(week.urls[3])!)
    }


    }```



移除强制展开,你就可以开始了。

@IBAction func Button1(_ sender: Any) {
    UIApplication.shared.open(week.urls[0])

}
@IBAction func Button2(_ sender: Any) {
    UIApplication.shared.open(week.urls[1])
}
@IBAction func Button3(_ sender: Any) {
    UIApplication.shared.open(week.urls[2])
}
@IBAction func Button4(_ sender: Any) {
   UIApplication.shared.open(week.urls[3])
}

前提是urls[URL]

给你...你的数组中已经有 URL...所以不需要再次创建它们...而且它们不是可选的...所以你不需要使用强制展开

 @IBAction func Button1(_ sender: Any) {
        UIApplication.shared.open(week.urls[0])

    }
    @IBAction func Button2(_ sender: Any) {
        UIApplication.shared.open((week.urls[1])
    }
    @IBAction func Button3(_ sender: Any) {
        UIApplication.shared.open(week.urls[2])
    }
    @IBAction func Button4(_ sender: Any) {
       UIApplication.shared.open(week.urls[3])
    }

最好使用一个功能而不是 4 个...只需设置按钮标签

 @IBAction func ButtonTapped(_ sender: UIButton) {
            UIApplication.shared.open(week.urls[sender.tag])

        }