我想用不同的URL链接每个单元格

时间:2018-07-27 09:51:34

标签: ios arrays swift uitableview

我有一个tableView,当用户单击单元格时,每个单元格应打开一个不同的URL enter image description here

这是代码:

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
}

2 个答案:

答案 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)
}