【问题标题】:An array from URLs in Objective-C来自 Objective-C 中 URL 的数组
【发布时间】:2015-05-26 21:04:48
【问题描述】:

我想解决 URL 的数组问题。 我在我的应用程序中使用 JSON,并且我有一组单元格。 我的目标:如果您单击任何单元格,页面将在 Safari 中打开,其中包含来自 JSON 数组的 URL。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier =@"LocationCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
    Location *location = [_locations objectAtIndex:indexPath.row];

    //...

    myCell.userInteractionEnabled = YES;
    UITapGestureRecognizer *gestureRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openUrl:)];
    gestureRec.numberOfTouchesRequired = 1;
    gestureRec.numberOfTapsRequired = 1;
    [myCell addGestureRecognizer:gestureRec];

    return cell;
}

- (void) openUrl: (id)sender: (Location *) location {
    UIGestureRecognizer *rec = (UIGestureRecognizer *)sender;
    id hitLabel = [self.view hitTest:[rec locationInView:self.view] withEvent:UIEventTypeTouches];

    if ([hitLabel isKindOfClass:[UILabel class]]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString: location.url]];
    }
}

出了点问题,因为应用程序因此错误而崩溃:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController openUrl:]: unrecognized selector sent to instance 0x7fd3a850ad40'

但是如果我在 UITableViewCell 中这样写:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString: location.url]];

应用程序启动时,链接将立即在 Safari 中打开。所以我认为JSON解析是正确的。

【问题讨论】:

  • 某处,您设法将openURL: 消息发送到您的ViewController 类而不是您的UIApplication
  • 我认为值得一提的是 -openURL:sender:location 的语法是......好吧,至少可以说很奇怪。它会生成以下警告:'sender used as the name of the previous parameter 而不是作为选择器的一部分'。

标签: ios objective-c arrays uitableview parsing


【解决方案1】:

你已经在你的ViewController中实现了这个方法

- (void) openUrl:(id) sender:(Location *)location

但你正在分配

@selector(openUrl:)

作为手势识别器的目标。这是另一种方法,因为缺少sender 参数。

也就是说,您不需要手势识别器;只需实现UITableViewDelegatedidSelectRowAtIndexPath:方法即可:

- (void)tableView:(UITableView)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     Location *location = [_locations objectAtIndex:indexPath.row];
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString: location.url]];
}

(如果您真的希望 URL 仅在用户点击标签时打开,而不是单元格的其余部分,您确实需要手势识别器。不过,这是非常糟糕的用户体验。)

【讨论】:

  • 哇,真的好用!惊人的!非常感谢,格洛芬德尔!
猜你喜欢
  • 2023-03-31
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多