【问题标题】:Why Image is not Shown in cellforRowAtIndexPath in objective C为什么图像未显示在目标 C 的 cellforRowAtIndexPath 中
【发布时间】:2017-02-07 07:04:22
【问题描述】:

我是 iOS 新手,我遇到了关于在 Web 服务的图像视图中显示图像的问题。我正在使用这样的代码

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *STI=@"STI";
    NewsTableViewCell *cell = (NewsTableViewCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"NewsTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell.accessoryType=UITableViewCellAccessoryNone;
    }

    NSString *strImgURLAsString = [NewsImageArray objectAtIndex:indexPath.row];
    [strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *imgURL = [NSURL URLWithString:strImgURLAsString];
    [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {
            img = [[UIImage alloc] initWithData:data];
            if (img==nil) {
               // img=[UIImage imageNamed:@"userimage.png"];
            }
            cell.newsimage.image=img;

            // pass the img to your imageview
        }else{
            NSLog(@"%@",connectionError);
        }
    }];

    cell.Headlbl.text=[NSString stringWithFormat:@"%@",[headarray objectAtIndex:indexPath.row]];

    NSString *aux = [shortnamearray objectAtIndex:indexPath.row];
    NSString * htmlString = @"<html><body>";
    NSString *htmlString2=@"</body></html>";
    NSString * NewString=[NSString stringWithFormat:@"%@%@%@",htmlString,aux,htmlString2];

    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[NewString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

    cell.bodylbl.attributedText=attrStr;
    cell.bodylbl.textAlignment=NSTextAlignmentCenter;
    cell.bodylbl.textColor=[UIColor whiteColor];
    [cell.bodylbl setFont:[UIFont fontWithName:@"Arial" size:16]];

    cell.backgroundColor = cell.contentView.backgroundColor;


   // cell.bodylbl.text=[NSString stringWithFormat:@"%@",[shortnamearray objectAtIndex:indexPath.row]];
 //   cell.randrid.text=[NSString stringWithFormat:@"%@",[idarray objectAtIndex:indexPath.row]];
    return cell;

}

图像路径 - http://qaec.teams.in.net/UploadedFiles/TommySchaefer,他在杀戮中所扮演的角色,他为此服务了 18 年.png

http://qaec.teams.in.net/UploadedFiles/Tommy%20Schaefer,%20of%20his%20role%20in%20the%20slaying,%20for%20which%20he%20is%20serving%2018%20year.png

当图像不包含任何间隙时,它显示图像 但是当图像包含任何间隙时,它不会显示图像。如何解决这个问题。提前致谢!

【问题讨论】:

  • 尝试在主线程中设置图像:dispatch_async(dispatch_get_main_queue(), ^{ cell.newsimage.image=img; });
  • 请添加不显示的图像画面
  • @nynohu 不工作。
  • @Muju 试试这个 cell.newsimage.image=[UIImage imageWithData:data]]
  • @Muju 你也可以试试SDWebImage,你需要传入url和默认图片,还要先检查数据长度

标签: ios objective-c web-services uitableview uiimageview


【解决方案1】:

您可以在 UITableviewCell 类中使用以下方法。在您的情况下,在 NewsTableViewCell.m 中添加代码当创建单元格时,调用 drowRect 方法。因此,在此方法中,您需要设置将图像设置为 YES 的图像视图的 setClipsToBounds 属性。这将解决您的问题。

-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    self.profilePicImgView.layer.cornerRadius=self.profilePicImgView.frame.size.width/2;
    [self.profilePicImgView setClipsToBounds:YES];
    [self.profilePicImgView layoutIfNeeded];
    [self.profilePicImgView setNeedsDisplay];
}

【讨论】:

    【解决方案2】:

    没有必要使用任何其他库等。你的代码在这一行是错误的:

    [strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    

    看看这个有什么作用?没有。您应该将变量 strImgURLAsString 重新分配给它,然后它应该可以工作:

     strImgURLAsString = [strImgURLAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    

    【讨论】:

    • 不行不行。仍然没有显示图像。
    • 这很奇怪,我刚刚在 xcode 中测试过,它可以工作。图片很大,请稍等。
    • 不确定为什么代码在我的 xcode 中有效,而在您的 xcode 中无效。这很奇怪,因为我复制了您的代码并仅修改“strImgURLAsString =”并且它可以工作。
    • 很高兴为您提供帮助。
    【解决方案3】:

    为了获得更好的性能,您可以试试这个名为 SDWebImage 的库。

    [imageView sd_setImageWithURL:[NSURL URLWithString:@"http://qaec.teams.in.net/UploadedFiles/Tommy%20Schaefer,%20of%20his%20role%20in%20the%20slaying,%20for%20which%20he%20is%20serving%2018%20year.png"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    还有 您需要确保已将其写入 plist 文件中

    【讨论】:

      【解决方案4】:

      这样使用:

      [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:imgURL] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
             if (!connectionError) {
      
                dispatch_async(dispatch_get_main_queue(), ^{
                  img = [[UIImage alloc] initWithData:data];
                  if (img==nil) {
                     // img=[UIImage imageNamed:@"userimage.png"];
                  }
                  cell.newsimage.image=img;
      
                  // pass the img to your imageview
                });
              }else{
                  NSLog(@"%@",connectionError);
              }
          }];
      

      【讨论】:

        【解决方案5】:

        我知道像您编写的那样在 Imageview 中加载图像 url 以更好地理解过程是个好主意。但是维护缓存也是需要考虑的重要事项。为了获得更好的性能,我建议您使用一个非常好的库,名为 SDWebImage。它的缓存机制可以帮助您更快地加载图像。试试这个。有了这个库,就这么简单。

        [imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                 placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        

        这是另一个。 如果您在应用中使用 AFNetworking,请使用以下代码来执行此操作。

         AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
        requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
        [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"Response: %@", responseObject);
            _imageView.image = responseObject;
        
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Image error: %@", error);
        }];
        [requestOperation start];
        

        【讨论】:

          猜你喜欢
          • 2020-08-01
          • 1970-01-01
          • 2017-11-01
          • 1970-01-01
          • 2020-12-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多