如何在内容(文本)量之后扩展UITableViewCell?

时间:2012-10-27 20:33:28

标签: ios uitableview

我如何实现这一目标?找不到有关此事的任何有用信息....我的应用程序中有一个论坛,并且根据帖子的大小,单元格应该在文本量之后缩放...是否可以将其设置为故事板还是你被迫编程呢? /问候

编辑以下是tableView中的代码。单元格有3个标签,2个或多或少是静态的(总是相同的文本数量),第3个是动态的(commentLabel),它可以包含例如1行到70行之间的所有内容。现在我想在评论标签的高度之后扩展单元格...

#import "ForumthreadViewController.h"

@interface ForumthreadViewController ()

@end

@implementation ForumthreadViewController

@synthesize tableView;
@synthesize textField;

@synthesize refreshButton;

@synthesize forumThreadDataProvider;

@synthesize dateFormatter;

@synthesize items;
@synthesize taskId;
@synthesize forumThreadId;

- (void)viewDidLoad
{
[super viewDidLoad];

self.forumThreadDataProvider = [[MLForumThreadDataProvider alloc] initWithDelegate:self];

self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:self.refreshButton, [self initLoadingIndicator], nil];

NSLocale *locale = [NSLocale currentLocale];
self.dateFormatter = [[NSDateFormatter alloc] init]; 
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"E MMM d" options:0 locale:locale];
[self.dateFormatter setDateFormat:dateFormat];
[self.dateFormatter setLocale:locale];

[self refreshData];
}

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

 - (BOOL)hidesBottomBarWhenPushed
{
return TRUE;
}

- (void)setLoadingState : (BOOL)loading
{
[super setLoadingState:loading];
if (loading)
{
    [self.refreshButton setEnabled:NO];
}
else
{
    [self.refreshButton setEnabled:YES];
}
}

 #pragma mark - Text field

- (void)textFieldDidBeginEditing:(UITextField *)pTextField
{
[self animateTextField: pTextField up: YES];
}

- (void)textFieldDidEndEditing:(UITextField *)pTextField
{
[self animateTextField: pTextField up: NO];
[pTextField resignFirstResponder];
}

- (void) animateTextField: (UITextField*) pTextField up: (BOOL) up
{
const int movementDistance = 215; // tweak as needed
const float movementDuration = 0.3f; // tweak as needed

int movement = (up ? -movementDistance : movementDistance);

[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}

- (BOOL)textFieldShouldReturn:(UITextField *)pTextField
{
[self setLoadingState:YES];
[pTextField resignFirstResponder];

NSUserDefaults *userStorage = [NSUserDefaults standardUserDefaults];

NSString *alias = [self urlEncode:[userStorage objectForKey:@"alias"]];
NSString *email = [self urlEncode:[userStorage objectForKey:@"email"]];
NSString *who = [self getUniqueDeviceId];
NSString *comment = [self urlEncode:[pTextField text]];

comment = [comment stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
who = [who stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

if([self isBlank:comment])
{
    [self setLoadingState:NO];
    pTextField.text = @"";
    return NO;
}
if([self isBlank:alias])
{
    [self showMessagePopup:NSLocalizedString(@"MessageMustChooseAlias", nil)];
    return NO;
}

[self.forumThreadDataProvider startSendPost:self.taskId : self.forumThreadId : alias : who : email : comment];

pTextField.text = @"";

return YES;
}

#pragma mark - Table view data source

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.items count];
}

- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"ForumthreadCell";
UITableViewCell *cell = [pTableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        }

Feedback *item = [self.items objectAtIndex:indexPath.row];

UILabel *aliasLabel = (UILabel *)[cell viewWithTag:1];
UILabel *commentLabel = (UILabel *)[cell viewWithTag:2];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:3];



[aliasLabel setText:item.alias];
[commentLabel setText:item.comment];
[dateLabel setText:[self.dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:(double)item.time]]];

commentLabel.numberOfLines = 0;
// commentLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
//commentLabel.lineBreakMode = UILineBreakModeWordWrap;
[commentLabel sizeToFit];

// CGSize constraint = CGSizeMake(300, 2000);
// CGSize size = [item.comment sizeWithFont:[UIFont boldSystemFontOfSize:11] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
//[commentLabel setFrame:CGRectMake(16, 30, 300, size.height)];

return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];

if (cell) {        
    UILabel *commentLabel = (UILabel *)[cell viewWithTag:2];
    return commentLabel.frame.size.height;
}  
else
   return 30;
}



#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

#pragma mark - Fetch data

- (IBAction) refreshData
{
[self setLoadingState:YES];
[self.forumThreadDataProvider startFetchResult:self.taskId : self.forumThreadId];

//[self fetchForumPosts:self.taskId : self.feedbackId];
}

 - (void) onFetchResultDone : (NSArray *) result
{
self.items = result;
[self.tableView reloadData];
[self setLoadingState:NO];
}

- (void) onCreatePostDone : (Result *) result
{
if ([result success])
{
    [self refreshData];
}
else
{
    [self showMessagePopup:[NSString stringWithFormat:NSLocalizedString(@"MessageErrorCreateForumPost", nil), result.code]];
}
[self setLoadingState:NO];
}

 - (void) onForumRequestFail : (NSError *) result
{
[self showNoConnectionPopup];
[self setLoadingState:NO];
}

错误图片: http://tinypic.com/view.php?pic=1jssyc&s=6

1 个答案:

答案 0 :(得分:1)

你将不得不以编程方式执行此操作。

为此,您需要在tableView:heightForRowAtIndexPath:代表中实施UITableView。这将为您提供表视图实例,以及相关行的索引路径。

更新为了做到这一点,您需要在创建单元格时根据其索引路径跟踪单元格的高度。你可以这样实现它:

@interface ForumthreadViewController() {
    NSMutableDictionary* m_cellHeights;
}
@end

// Init your dictionary in your init method using m_cellHeights = [NSMutableDictionary alloc] init];

- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    [commentLabel setText:item.comment];
    [dateLabel setText:[self.dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:(double)item.time]]];

    commentLabel.numberOfLines = 0;
    // commentLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
    //commentLabel.lineBreakMode = UILineBreakModeWordWrap;
    [commentLabel sizeToFit];

    [m_cellHeights setObject:@(commentLabel.frame.size.height) forKey:indexPath];
    ...
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSNumber* value = [m_cellHeights objectForKey:indexPath];

    if (value) {
        return [value floatValue];
    }

    return 0.0;
}

修改:通过查看您提供的代码,UILabel在哪里创建?

UILabel *aliasLabel = (UILabel *)[cell viewWithTag:1];
UILabel *commentLabel = (UILabel *)[cell viewWithTag:2];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:3];

此代码尝试从单元格中提取UILabel,但是在单元格生成代码中没有任何地方正在创建这些标签。您需要创建并添加它们(我使用...来防止从您的问题中重新打印过多的代码:

    - (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    ...

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        UILabel* newAlias = [[UILabel alloc] initWithFrame:...]; // Provide the frame you need
        newAlias.tag = 1;
        [cell.contentView newAlias];

        // Do the same for date and comment
    }

    Feedback *item = [self.items objectAtIndex:indexPath.row];

    UILabel *aliasLabel = (UILabel *)[cell.contentView viewWithTag:1];
    UILabel *commentLabel = (UILabel *)[cell.contentView viewWithTag:2];
    UILabel *dateLabel = (UILabel *)[cell.contentView viewWithTag:3];

    ...

    return cell;
}