将MKPlacemark addressDictionary添加到UITableViewCell

时间:2015-10-29 13:30:21

标签: ios swift uitableview cocoa-touch ios9

我正在尝试为我的UITableViewCell的textDetailLabel添加街道地址。我遇到的问题是如何捕获cell中每个Table View的唯一街道地址。

现在它正在抓取字典中第一个实例的第一个街道值,并将其设置为每个cell的街道地址。

我假设我需要捕获索引,然后从字典中检索街道值,尽管我不完全确定如何执行此操作。

这是我的代码

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "Cell")
    // searchResults is an array of MKMapItems
    cell.textLabel?.text = self.searchResults[indexPath.row].name

    // the line that is causing me trouble 
    cell.detailTextLabel?.text = placeMarkAddress["Street"] as? String ?? ""

    return cell

}


func searchQuery(query: String) {


    // request
    let request = MKLocalSearchRequest()
    request.naturalLanguageQuery = query
    request.region = mapView.region

    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    // search 
    let search = MKLocalSearch(request: request)
    search.startWithCompletionHandler { (response, error) -> Void in

        UIApplication.sharedApplication().networkActivityIndicatorVisible = false

        if(error != nil) {

            print(error?.localizedDescription)

        } else {

            // storing data about location in dictionary
            for item in (response?.mapItems)! {

                self.placeMarkAddress = item.placemark.addressDictionary!
                // prints expected results in console (not repeating, different for each MKMapItem)
                for (key,value) in self.placeMarkAddress {
                    print("\(key) -> \(value)")
                }
            }

            // storing the array of mkmapitems in the array
            self.searchResults = (response?.mapItems)!
        }


    }

}

Address repeating 街道地址不断重复

提前感谢您的任何帮助。

2 个答案:

答案 0 :(得分:2)

您需要创建" placeMarkAddress"。

的数组
var placeMarkAddress: NSMutableArray;

现在,在其中添加地址。

for item in (response?.mapItems)! {
               self.placeMarkAddress.addObject(item.placemark.addressDictionary!)

 }

答案 1 :(得分:0)

首先,您需要为MKmapItem's instance获取UITableViewCell,然后从street address找到MKmapItem's plcaemark

注意:Objective-C中的代码,以便快速进行

MKmapItem *mapItem = self.searchResults[indexPath.row];
NSDictionary *itemAddressDictionary = mapItem.placemark.addressDictionary;
//get required string from itemAddressDictionary and set in cell.detailTextLabel
NSString *strStreet = [itemAddressDictionary objectForKey:@"Street"];
cell.detailTextLabel.text = strStreet;