简体   繁体   English

UILabels隐藏在“图像视图”单元的后面吗?

[英]UILabels are Hidding behind the Image View cell?

Hi I have issue with Labels ,ie , I have a XML NewsViewController where i am displaying the News . 嗨,我对Labels有问题,即我有一个XML NewsViewController用来显示News。 You can see the Screen shot (NewsViewController.jpg) In NewsViewController i am displaying the Tittle, Date and Description labels , those labels are hiding behind the imageView cell But in the Few News List are displaying fine .Can any one Help me ?? 您可以看到屏幕截图(NewsViewController.jpg)在NewsViewController中,我正在显示标题,日期和描述标签,这些标签隐藏在imageView单元格的后面,但在“很少新闻列表”中显示的很好。

Below i have given the NewsViewController code please check 下面我给了NewsViewController代码,请检查

Here is my NewsViewController.m 这是我的NewsViewController.m

#import "NewsViewController.h"
#import "NewsTableViewCell.h"
#import "NewDetailsViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
@interface NewsViewController ()
{
    NSString *temString;
    NSMutableString *strTemp;
    BOOL isDateSearch;
}

@end

@implementation NewsViewController
@synthesize arrImages;
@synthesize TittleOne;
@synthesize TittleTwo;
@synthesize TittleThree;
@synthesize datepicker;
@synthesize PickerContainer;
@synthesize datepickerTittle;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

#pragma mark - View Life Cycle
- (void)viewDidLoad
{

    [super viewDidLoad];
    [TittleOne setFont: [UIFont fontWithName:@"GEEast-ExtraBold" size:12]];
    [TittleTwo setFont: [UIFont fontWithName:@"GEEast-ExtraBold" size:10]];
    [TittleThree setFont: [UIFont fontWithName:@"GEEast-ExtraBold" size:10]];
    // [[UIColor redColor] set];
    [datepickerTittle setFont:[UIFont fontWithName:@"GEEast-ExtraBold" size:12]];
    // [datepickerTittle.textColor= [UIColor yellowColor]];

    isDateSearch=NO;
    self.arrTitles =[[NSMutableArray alloc] init];
    self.arrDescription=[[NSMutableArray alloc]init];
    self.arrImages=[[NSMutableArray alloc]init];
    self.arrDate=[[NSMutableArray alloc]init];
    self.arrUrls=[[NSMutableArray alloc]init];
    self.arrDateSearch=[[NSMutableArray alloc]init];
    //[self performSelectorInBackground:@selector(requestingForNews:) withObject:nil];

    // dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), s^{
    self.spinnerView.hidden=YES;
    [self makeRequestForNews];
    //  self.spinnerView.stopAnimating;
    //});

    // Do any additional setup after loading the view.
    [self imagedownloader:@"http://www.shura.bh/MediaCenter/News/"];
}
-(void)requestingForNews:(id)sender
{
    [self makeRequestForNews];
}
-(void) imagedownloader : (NSString *)urlStringOfImage
{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
        //downlaod image
        NSURL *imageUrl = [NSURL URLWithString:urlStringOfImage];
        NSData  *imageData = [NSData dataWithContentsOfURL:imageUrl];
        UIImage *image = [UIImage imageWithData:imageData];
        dispatch_async(dispatch_get_main_queue(), ^{

            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50 )];
            imageView.image = image;
            [self.view addSubview:imageView];
        });
    });
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma  mark - make request for news
-(void)makeRequestForNews
{

    NSURL *url =[NSURL URLWithString:self.strNewsApi];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //After making request the apparent thing is expecting the response that may be expected response or an Error. so create those objects and intialize them with NULL.
    NSURLResponse *response = NULL;
    NSError *requestError =NULL;
    //Once you have response with you , Capture YOur Responce data using NsData.

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];

    //Convert the respnse Data into Response String.

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    //Now We can start parsing the Data using XMl parser . you need XML parser in-order to use the below class method "dictionaryFOrXMLString".

    NSError *parserError = NULL;

    //XML parsing

    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:responseData];
    [xmlParser setDelegate:self];
    [xmlParser parse];

    //    NSURL *url = [NSURL URLWithString:url];
    //    NSData *data = [NSData dataWithContentsOfURL:url];
    //    UIImage *image = [UIImage imageWithData:data];

    //NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:NULL];

    //once you have xmlDict handy, you can pass this to the any ViewController (Like table view) to populate the Data.
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {

}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{


    if ([elementName isEqualToString:@"ShuraNews"])
    {

    }
    if ([elementName isEqualToString:@"PUBLISHINGPAGEIMAGE"])
    {

    }
    strTemp=[NSMutableString new];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    //temString =string;
    [strTemp appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"TITLE"])
    {
        NSLog(@"temstring=== %@", strTemp);
        [self.arrTitles addObject:strTemp];
    }
    if ([elementName isEqualToString:@"PUBLISHINGPAGECONTENT"])
    {
        NSLog(@"temstring=== %@", strTemp);
        [self.arrDescription addObject:strTemp];
    }
    if ([elementName isEqualToString:@"NEWSARTICLEDATE"])
    {
        NSLog(@"temstring=== %@", strTemp);
        [self.arrDate addObject:strTemp];
    }
    if ([elementName isEqualToString:@"PUBLISHINGPAGEIMAGE"])
    {

        NSLog(@"temstring=== %@", strTemp);
        [self.arrImages addObject:strTemp];
    }
    if ([elementName isEqualToString:@"ShuraNews"])
    {
        [self.tblNews reloadData];
        // self.spinnerView.hidden=YES;
    }
    if ([elementName isEqualToString:@"URL"])
    {
        [self.arrUrls addObject:strTemp];
    }

}

#pragma mark - TabeView Datasource//delegate method

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (isDateSearch)
    {
        return [self.arrDateSearch count];
    }
    else{
        return [self.arrTitles count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setSeparatorInset:UIEdgeInsetsZero];
    static NSString *cellIdentifier=@"cellNews";
    NewsTableViewCell *cell=(NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    if (cell == nil)
    {
        cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        // cell.NewsTableViewCell.textColor = UIColorFromRGB(0x000000);
        cell.backgroundColor=[UIColor clearColor];


    }

    if( [indexPath row] % 2){
        cell.contentView.backgroundColor =UIColorFromRGB(0Xffffff);

    }
    else{
        cell.contentView.backgroundColor =UIColorFromRGB (0Xdcdcdc);
    }

    //selectbackground color start
    UIView *NewsTableViewCell = [[UIView alloc] initWithFrame:cell.frame];
    NewsTableViewCell.backgroundColor = UIColorFromRGB(0Xdcdcdc);
    cell.selectedBackgroundView = NewsTableViewCell; //select background colro end
    cell.lblTitles.font = [UIFont fontWithName:@"GEEast-ExtraBold" size:12];
    if (isDateSearch)
    {
        cell.lblTitles.text=[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:@"title"];
    }
    else{
        cell.lblTitles.text=[self.arrTitles objectAtIndex:indexPath.row];
    }
    cell.lblDescription.font =[UIFont fontWithName:@"GE SS Unique" size:12];
    cell.lblDate.font=[UIFont fontWithName:@"GE SS Unique" size:12];
    if (isDateSearch)
    {
        cell.lblDescription.text=[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:@"des"];
    }
    else{
        cell.lblDescription.text=[self.arrDescription objectAtIndex:indexPath.row];
    }
    cell.lblDate.text=[self.arrDate objectAtIndex:indexPath.row];
    cell.lblTitles.textAlignment= NSTextAlignmentRight;
    cell.lblDate.textAlignment = NSTextAlignmentRight;
    cell.lblDescription.textAlignment = NSTextAlignmentRight;
    //SDWebImage Code for lazy loader
    [cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:@""]];
    // cell.imgNews.image=[UIImage imageWithData:data];
    cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
    cell.imgNews.layer.borderWidth = 2.0;
    [PickerContainer setHidden:YES];
    if (!cell.imgNews.image)
    {
        cell.lblTitles.frame=CGRectMake(cell.lblTitles.frame.origin.x, cell.lblTitles.frame.origin.y, 283, cell.lblTitles.frame.size.height);
        cell.lblDate.frame=CGRectMake(cell.lblDate.frame.origin.x, cell.lblDate.frame.origin.y, 286, cell.lblDate.frame.size.height);
        cell.lblDescription.frame=CGRectMake(cell.lblDescription.frame.origin.x, cell.lblDescription.frame.origin.y, 281, cell.lblDescription.frame.size.height);
        cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
        cell.imgNews.layer.borderWidth = 0;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict=nil;
    if (isDateSearch)
    {
        //dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:@"%@",[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:@"title"]],@"title",[NSString stringWithFormat:@"%@",[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:@"des"]],@"img",[NSString stringWithFormat:@"%@",[self.arrDescription objectAtIndex:indexPath.row]],@"Des",[NSString stringWithFormat:@"%@",[self.arrUrls objectAtIndex:indexPath.row]],@"url", nil];
    }
    else{
        dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:@"%@",
                                                          [self.arrTitles objectAtIndex:indexPath.row]],@"title",[NSString stringWithFormat:@"%@",
                                                                                                                  [self.arrImages objectAtIndex:indexPath.row]],@"img",[NSString stringWithFormat:@"%@",
                                                                                                                                                                        [self.arrDescription objectAtIndex:indexPath.row]],@"Des",[NSString stringWithFormat:@"%@",[self.arrUrls objectAtIndex:indexPath.row]],@"url", nil];
    }
    [self performSegueWithIdentifier:@"NewsDetailsID" sender:dict];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"NewsDetailsID"])
    {
        ((NewDetailsViewController *)segue.destinationViewController).strTitle=[sender objectForKey:@"title"];
        ((NewDetailsViewController *)segue.destinationViewController).strDetailImage=[sender objectForKey:@"img"];
        ((NewDetailsViewController *)segue.destinationViewController).strDescription=[sender objectForKey:@"Des"];//strUrl
        ((NewDetailsViewController *)segue.destinationViewController).strUrl=[sender objectForKey:@"url"];
    }
}

- (IBAction)backBtnClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)DatePickerBt:(id)sender {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    PickerContainer.frame = CGRectMake(0, 150, 320, 261);
    [PickerContainer setHidden:NO];
}
- (IBAction)HideButton:(id)sender
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    PickerContainer.frame = CGRectMake(0,600, 320, 261);
    [UIView commitAnimations];

    if ([self.arrDateSearch count])
    {
        [self.arrDateSearch removeAllObjects];
    }
    if ([self.arrDate count])
    {
        for (int i=0; i<[self.arrDate count]; i++)
        {
            NSLog(@"arrdate === %@",self.arrDate);

            NSArray *arrDateStr=[[self.arrDate objectAtIndex:i] componentsSeparatedByString:@" "];
            NSArray *arrDat=[[NSString stringWithFormat:@"%@",[arrDateStr objectAtIndex:0]] componentsSeparatedByString:@"/"];

            NSString *strDat=[NSString stringWithFormat:@"%@-%@-%@",[arrDat objectAtIndex:2],[arrDat objectAtIndex:1],[arrDat objectAtIndex:0]];
            NSString *strPicDat=[[[NSString stringWithFormat:@"%@",self.datepicker.date]componentsSeparatedByString:@" "]objectAtIndex:0];
            NSLog(@" strpic date === %@",strPicDat);
            if ([strDat isEqualToString:strPicDat])
            {
                isDateSearch=YES;
                NSDictionary *dictTemp=[NSDictionary dictionaryWithObjectsAndKeys:[self.arrTitles objectAtIndex:i],@"title",[self.arrDescription objectAtIndex:i],@"des",[self.arrImages objectAtIndex:i],@"img", nil];
                [self.arrDateSearch addObject:dictTemp];
                NSLog(@"dates equal");
            }

        }

        [self.tblNews reloadData];

    }
}
- (IBAction)ReloadButton:(id)sender {


}
@end

Below i have given the Screen shots 下面我给出了屏幕截图

NewsViewController Link Here NewsViewController 链接在这里

DetailsViewController Link here DetailsViewController 链接在这里

There are two questions here. 这里有两个问题。 Ill answer the one about the tableview. 我不愿回答有关tableview的问题。

The SDWebImage category on UIImageView ( UIImageView+WebCache ) is an async API , hence when you work out whether there is an image there and arrange your text frame it always evaluates to NO UIImageViewUIImageView+WebCache )上的SDWebImage类别是一个异步API,因此,当您确定那里是否有图像并排列文本框架时,它总是评估为NO

[cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:@""]];
...
if (!cell.imgNews.image)
{
    //setup text frame
}

what you are calling is a convenience method for this... 您所说的是为此的一种便捷方法...

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletedBlock)completedBlock;

so try this... 所以试试这个...

[cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]] 
placeholderImage:[UIImage imageNamed:@""] 
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
    ...
    if (image) {
    //setup text frame for image
    }
    else {
   //setup text for no image as cell is recycled and may have held image previously
    }

}];

Please view your InterfaceBuilder Screenshots 2 and 3. 请查看您的InterfaceBuilder屏幕截图2和3。

The Large image (3) has the autoresizing mask set so that the margin to the right is maintained. 大图(3)设置了自动调整大小蒙版,以便保持右边距。 # It looks like this #看起来像这样

_ | _ | _ _

The Label besides the small image in the UITableViewCell however only mainains the margins to the top and the left. 标签除了UITableViewCell中的小图像外,仅维护顶部和左侧的边距。 Set to keep it on the right as well and it won't overflow anymore. 设置它也保持在正确的位置,它将不再溢出。 Make it look like the mask above. 使它看起来像上面的面具。

Of course you'd have to do this for all 3 labels. 当然,您必须对所有3个标签都这样做。 Alternatvively you could wrap the 3 labels in a view and only do the autoresizing mask stuff for this container and make the labels fill out the entire width of the container. 或者,您可以将3个标签包裹在一个视图中,并且仅对此容器进行自动调整大小的遮罩填充物,并使标签填充容器的整个宽度。

I will answer the question regarding the cells in "NewsViewController". 我将回答有关“ NewsViewController”中单元格的问题。 Using [UIImage imageNamed:@""] is equivalent to passing nil . 使用[UIImage imageNamed:@""]等效于传递nil UIImage class will not find an image with a name of empty string, so it will return nil . UIImage类将找不到名称为空字符串的图像,因此它将返回nil When you check cell.imgNews 's image, it will be nil as the real image is still not loaded yet. 当您检查cell.imgNews的图像时,它将nil因为尚未加载实际图像。

You have two options: 1- Use a placeholder image. 您有两个选择:1-使用占位符图像。 2- Check for the image url instead of the image itself. 2-检查图像的URL,而不是图像本身。 like if (![self.arrImages objectAtIndex:indexPath.row]) . 就像if (![self.arrImages objectAtIndex:indexPath.row])

Note: Make sure the data arrays have the same length. 注意:确保数据数组的长度相同。 If one of them has different length, you will get out of bounds exception. 如果其中一个具有不同的长度,则将超出范围例外。 One way of solving this is using a custom class that hold all related information. 解决此问题的一种方法是使用包含所有相关信息的自定义类。 Then build an array of it. 然后构建一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM