2016-03-11 36 views
0

我在包含標籤和imageView的高度爲300的故事板中製作了一個自定義單元格,但對於某些情況下,如果我沒有收到響應圖像,我想降低單元格高度並想從單元格中移除imageView因此用戶無法看到它。 在這種情況下,我只想顯示標籤中的文字。 我怎麼能做到這一點?我知道這個愚蠢的問題,但我被困在這裏。 您的幫助,將不勝感激。 謝謝如何在Objective C中減少運行時UITableViewCell的大小?

+0

只需在heightForRowAtIndexPath上添加條件即可。 如果圖像不存在然後降低高度 –

+0

但在imageview下我也有按鈕...如果我降低高度它也會隱藏它。 –

+0

然後,您需要更改cellforrowatindexpath中按鈕的框架。相應地減少按鈕的y值。 –

回答

0

我已經寫了一些基本的代碼來了解如何表視圖單元格調整大小工作(不相關的自定義或基本單元格)。

@interface MasterViewController() 

@property NSArray *objects; 
@end 

@implementation MasterViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    _objects = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ImageList" ofType:@"plist"]]; 
} 


- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 
} 

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

#pragma mark - Table View 

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return _objects.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 

    NSDictionary *object = _objects[indexPath.row]; 
    cell.textLabel.text = object[@"text"]; 
    cell.imageView.image = [UIImage imageNamed:object[@"image"]]; 
    return cell; 
} 

//- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
// return _objects.allKeys[section]; 
//} 

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { 
    // Return NO if you do not want the specified item to be editable. 
    return YES; 
} 

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    return [_objects[indexPath.row][@"image"] length] ? 60.0f : 30.0f; 
} 

@end 

在上面的代碼中,你首要重點應放在方法heightForRowAtIndexPath,它的代碼行return [_objects[indexPath.row][@"image"] length] ? 60.0f : 30.0f;

現在好像您從服務器動態加載圖像,然後跟蹤已加載哪個單元的圖像,並呼叫[tableView reloadRowsAtIndexPaths:<#(nonnull NSArray<NSIndexPath *> *)#> withRowAnimation:<#(UITableViewRowAnimation)#>]以及相關索引路徑。同時請確保您在dataSource中更新image loaded信息,即上述代碼中的_objects

我已經上傳code here。在工作區檢查UITableViewTest