在DetailTextLabel中显示位置

时间:2013-08-02 01:06:31

标签: ios location tableview

我正在构建一个在桌面视图中显示帖子的iPhone应用程序。每个帖子都标有用户的当前位置,我很难在详细文本标签中显示。 帖子模型包括这些属性

@property (nonatomic, strong) NSString *content;
@property (strong) CLLocation *location;

在索引视图中,我像这样配置单元格:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    [self configureCell:cell forRowAtIndexPath:indexPath];
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    Post *post = [self.posts objectAtIndex:indexPath.row];

    cell.textLabel.numberOfLines = 0;
    cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    cell.textLabel.text = post.content;

这会正确返回帖子的内容。 但是,当我尝试在字幕中包含lat / lng时,它会崩溃。 这会导致崩溃并引发不兼容的指针类型异常“来自CLLocation的NSString”:

cell.detailTextLabel.text = post.location;

这是有道理的,因为.text期望一个字符串和位置在字典中初始化,如下所示:

- (id)initWithDictionary:(NSDictionary *)dictionary {
    self = [super init];
    if (!self) {
        return nil;
    }

    self.content = [dictionary valueForKey:@"content"];
    self.location = [[CLLocation alloc] initWithLatitude:[[dictionary nonNullValueForKeyPath:@"lat"] doubleValue] longitude:[[dictionary nonNullValueForKeyPath:@"lng"] doubleValue]];

    return self;
}

那么如何在字幕标签中返回位置? 我还想显示一个时间戳,并怀疑它是一个类似的解决方案。 在我的帖子模型实现文件中我#import“ISO8601DateFormatter.h”从日期格式化字符串,同样我有:

static NSString * NSStringFromCoordinate(CLLocationCoordinate2D coordinate) {
    return [ NSString stringWithFormat:@"(%f, %f)", coordinate.latitude, coordinate.longitude];
}

但我不知道如何将这一切都绑定到一个简单的detailTextLabel。

非常感谢任何帮助。

修改

我做了这么多进步: lat和lng显示整数 - 但它不是正确的lat / lng,即它实际上没有读取正确的整数。

cell.detailTextLabel.text = [NSString stringWithFormat:@"at (%f, %f)", post.location];

显示的lat和lng是这样的: 0.00,-1.9 应该是什么时候: LAT “:” 37.785834" , “LNG”:“ - 122.406417。 所以它实际上没有读到“post.location”这一行的结尾 那么如何让它显示正确的数据呢?

1 个答案:

答案 0 :(得分:0)

你试过这个吗?

   - (void)configureCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
        Post *post = [self.posts objectAtIndex:indexPath.row];

        cell.detailTextLabel.text  = NSStringFromCoordinate(post.location);
        //.....more setup code
    }