2017-08-31 45 views
0

我创建了一个UiTableViewController与四个部分和每个行数。我也实现了一组URL。我是新来的编码,这是前两个TableViewControllers工作的组合,但我遇到的问题是URL数组适用于每个部分。即当单击第1部分中的第1行时,它将打开第一个链接,但它也会在单击第2部分中的第1行时打开第一个链接。URL链接是UiTableView与多个部分

如何将URL数组限制为仅一个部分?

我明白为什么它不工作,并尝试了很多东西,但没有得到它。

struct Objects { 
    var sectionName : String! 
    var sectionObjects :[String]! 
} 

var objectsArray = [Objects]() 

let urlArray1 = ["http://www.apple.co.uk","http://www.google.co.uk","https://www.dropbox.com/","tel://123456789",""] 

override func viewDidLoad() { 
    super.viewDidLoad() 

    objectsArray = [Objects(sectionName: "Section 1", sectionObjects: ["one", "two", "three", "four","four A"]), 
        Objects(sectionName: "Section 2", sectionObjects: ["five", "six", "seven", "eight"]), 
        Objects(sectionName: "Section 3", sectionObjects: ["nine", "ten", "eleven", "twelve"]), 
        Objects(sectionName: "Section 4", sectionObjects: ["thirteen", "fourteen", "fifteen", "sixteen"])] 
} 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as UITableViewCell! 

    cell?.textLabel?.text = objectsArray[indexPath.section].sectionObjects[indexPath.row] 

    return cell! 
} 

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return objectsArray[section].sectionObjects.count 
} 

override func numberOfSections(in tableView: UITableView) -> Int { 
    return objectsArray.count 
} 

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return objectsArray[section].sectionName 
} 

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let urlString = self.urlArray1[indexPath.row] 
    if let url = URL(string:urlString) 
    { 
     UIApplication.shared.open(url, options: [:]) 
    } 

回答

0

您的urlArray1需要设置为单独的部分。

当您拨打let urlString = self.urlArray1[indexPath.row]它只取决于行,而不是部分。所以(部分0,行0),(部分1,行0),(部分2,行0)等都返回相同的值。

我将URL属性添加到您的Object结构:

struct Objects { 
    var sectionName: String 
    var sectionObjects: [String] 
    var urlStrings: [String] 
} 

然后你就可以访问相应的一个,像这样:

let urlString = objectsArray[indexPath.section].urlStrings[indexPath.row] 

(请确保您的objectsArray定义urlStrings

相关问题