IOS - 根据内容调整单元格高度

时间:2015-06-22 04:17:31

标签: ios uitableview autolayout

我试图构建具有类似于twitter的tableview单元格的应用程序,有文本和图像。 我的问题是我想在文本上方插入图像。虽然它可以只是文本。 因此,如果没有图像,则文本将位于(0,0)位置。如果有图像,它将是(0,306)位置。

我是否必须以编程方式使用或使用自动布局?

欣赏答案。感谢..

4 个答案:

答案 0 :(得分:1)

如果使用AutoLayout,请使用此代码

您尝试设置div.blue属性UITableView

estimatedHeight

其他明智的使用此-(void)viewWillAppear:(BOOL)animated{ _messageField.delegate = self; _tableView.estimatedRowHeight = 65.0; _tableView.rowHeight = UITableViewAutomaticDimension; } 委托方法

UITableView

答案 1 :(得分:0)

最好以编程方式使用此委托

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

答案 2 :(得分:0)

使用AutoLayout,只需获取NSLayoutConstraint并将其绑定到标签的Top Space约束。您还需要计算标签的大小,以根据内容调整单元格高度。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //If image exists, set the value of the constraint to 306, else set it to 0
    constraintName.constant = 306;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{        
    CGFloat labelHeight = [self findHeightForText:labelMe.text havingWidth:labelWidth andFont:[UIFont systemFontOfSize:22];
    return labelHeight + paddingHeight;
}



//Method to calculate label height
- (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
    CGSize size = CGSizeZero;
    if (text) {
    #ifdef __IPHONE_7_0
        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height);
    #else
        size = [text sizeWithFont:font constrainedToSize:CGSizeMake(widthValue, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
    #endif
    }
    return size.height;
}

答案 3 :(得分:0)

试试这个

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //calculating the height according to the device height.
    return self.view.frame.size.height * (102.0 / 568.0);
}

其中102.0将是当前高度,根据当前设计的xib高度568.0。这将根据高度调整单元格的大小。

相关问题