无法分配给searchResultsTableView的自定义单元格的UILabel

时间:2013-12-07 09:08:13

标签: ios iphone uitableview

一切正常但无法为searchResultsTableView的自定义单元格的UILable赋值。我为我的表视图控制器使用相同的自定义UITableViewCell,它是searchDisplayController。我正在使用storyboard作为表视图控制器和表视图单元格。正如您在代码中看到的,如果我NSLog的值为self.searchResults [indexPath.row] [@“name”],我可以在控制台中看到结果,但是如果我将此值赋给cell.name.text ,它不会工作,但在表视图控制器中,它的工作。单元格的imageView正在工作,我无法为单元格的UILabel分配任何值。

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.searchDisplayController.searchResultsTableView registerClass:[LocalCell class] forCellReuseIdentifier:@"Cell2"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    static NSString *CellIdentifier2 = @"Cell2";

    if (tableView == self.searchDisplayController.searchResultsTableView) {
        LocalCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2 forIndexPath:indexPath];
        if (!cell) {
            cell = [[LocalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
        }
        cell.name.text = self.searchResults[indexPath.row][@"name"];
        NSLog(@"%@", self.searchResults[indexPath.row][@"name"]); // has value
        NSLog(@"%@", cell.name.text); // null
        return cell;

    } else
    {
        LocalCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        if (!cell) {
            cell = [[LocalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        cell.name.text = self.restaurants[indexPath.row][@"name"];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return 80;

}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    float radius = 1000.0f;
    NSString *searchContent = [searchBar.text stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

    if ([searchContent length] > 0) {
        NSString *urlString = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=%f&types=food&key=%@&sensor=true&name=%@", [[[NSUserDefaults standardUserDefaults] objectForKey:@"lat"] floatValue], [[[NSUserDefaults standardUserDefaults] objectForKey:@"lon"] floatValue], radius, AppKey, searchContent];
        __weak LocalViewController *weakSelf = self;
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

        NSURLSessionDataTask *taks = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            if (!error) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                weakSelf.nextPageToken = dict[@"next_page_token"];
                weakSelf.searchResults = dict[@"results"];
                NSLog(@"search results: %@", weakSelf.searchResults);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.searchDisplayController.searchResultsTableView reloadData];
                });
            }

        }];
        [taks resume];
    }
}

LocalCell.h

#import <UIKit/UIKit.h>

@interface LocalCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UILabel *name;

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *desc;
@property (weak, nonatomic) IBOutlet UILabel *distance;

@end

1 个答案:

答案 0 :(得分:2)

我查看了你的项目:

NSLog(@"%@", cell.name.text); // null 

因为cell.name是nil。 解释是:然后你加载你的普通tableView,单元格“LocalCell”从Storyboard加载,分配和初始化你的标签,但是你使用self.searchDisplayController.searchResultsTableView初始化“LoadCell”,但从不初始化他的标签(因为他们是弱IBOutlets - 并用于故事板。)

为了解决您的问题,我找到了3个解决方案: 1.创建另一个具有对其UILabel的强引用的SearchCell,初始化SearchCell的所有UILabel - (id)init。然后在你的控制器中使用它。

[self.searchDisplayController.searchResultsTableView registerClass:[SearchCell class] forCellReuseIdentifier:@"SearchCell"];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    static NSString *SearchCellIdentifier = @"SearchCell";

    Restaurant *res;

if (tableView == self.searchDisplayController.searchResultsTableView)
{
    SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:SearchCellIdentifier forIndexPath:indexPath];
    if (!cell) {
        cell = [[SearchCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    res = (Restaurant *)self.searchResults[indexPath.row];

    cell.nameLabel.text = res.name;
    cell.descLabel.text = res.desc;

    // image load

    return cell;
}
else
{
    LocalCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if (!cell) {
        cell = [[LocalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    res = (Restaurant *)self.restaurants[indexPath.row];

    cell.nameLabel.text = res.name;
    cell.descLabel.text = res.desc;

    // image load

    return cell;
}
}

另一种方法是使用您的单元格“SearchCellNib”创建一个nib,并使用您创建的LoadCell类。对于加载笔尖使用:

cell = (LoadCell*)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = (LoadCell*)[[[NSBundle mainBundle] loadNibNamed:@"SearchCellNib" owner:nil options:nil] objectAtIndex:0];
    }

或使用UITableViewCell

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SearchCellIdentifier forIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    res = (Restaurant *)self.searchResults[indexPath.row];

    cell.textLabel.text = res.name;
    cell.detailTextLabel.text = res.desc;