我有一个tableView,当用户单击单元格时,每个单元格应打开一个不同的URL
这是代码:
var mathLessons = [["1"],["2"],["3"],["4"]]
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.textLabel?.text = lessons.mathLessons[indexPath.section][indexPath.row]
return cell
}
答案 0 :(得分:0)
您可以使用UITableView's didSelectRowAt
的委托
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// create url from string
if let url = URL(string: mathLessons[indexPath.row]) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
更新
用您的mathLessons[indexPath.row]
变量更改url
答案 1 :(得分:0)
使用自定义结构来保存课程编号和相应的URL
struct Lesson {
let number : String
let url : URL
}
var mathLessons = [Lesson(number: "1", url: URL(string:"https://...1")!),
Lesson(number: "2", url: URL(string:"https://...2")!),
Lesson(number: "3", url: URL(string:"https://...3")!),
Lesson(number: "4", url: URL(string:"https://...4")!)]
在cellForRow
中显示数字
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.textLabel?.text = lessons.mathLessons[indexPath.section][indexPath.row].number
return cell
}
在didSelect
中打开相应的URL
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let url = lessons.mathLessons[indexPath.section][indexPath.row].url
UIApplication.shared.open(url)
}