以编程方式使用自动布局如何在ios中为UItableView单元格和UItextView设置动态高度

时间:2015-07-21 14:38:05

标签: ios objective-c

您好我是Ios的初学者我在UItableview单元格上设置了UItextview,但根据我的要求,我必须根据文本数据动态设置UItextview和UItableview单元格高度,我的代码在下面根据我的代码6加屏幕即将到来比如第一张图片enter image description here

我的代码如下:

#import "ViewController.h"

@interface ViewController ()
{
    UITableView * MaintableView;
    NSArray * mainArray;
    NSArray * aboutArray;
    NSArray * formulaArray;

    //UItextFields
    UITextField * firstName;
    UITextField * secondName;
    UITextField * thirdName;
    UITextField * fourthName;
    UITextField * fifthName;
    UITextField * sixthName;
    UITextField * seventhName;
    UITextField * eightName;
    UITextField * ninthName;

    //UILabels
    UILabel * firstLabel;
    UILabel * secondLabel;
    UILabel * thirdLabel;
    UILabel * fourthLabel;
    UILabel * fifthLabel;
    UILabel * sixthLabel;
    UILabel * seventhLabel;
    UILabel * eigthLabel;
    UILabel * ninthLabel;

    //UItextViews
    UITextView * formulaText;
    UITextView * aboutText;

}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    mainArray = [NSArray arrayWithObjects:@"1",@"2",@"3",nil];

    aboutArray = [[NSArray alloc]init];
    formulaArray = [[NSArray alloc]init];

    aboutArray = [NSArray arrayWithObjects:@"The server encountered an error while trying to process the request. You could retry the same request following the requirements listed in Timeout (see row above). If the error persists, please report the problem in the android-gcm group.The server encountered an error while trying to process the request. You could retry",@"The server encountered an error while trying to process the request. You could retry the same request following the requirements listed in Timeout (see row above). If the error persists, please report the problem in the android-gcm group.The server encountered an error while trying to process the request. You could retry the same request following the requirements listed in Timeout (see row above). If the error persists, please report the problem in the android-gcm group.The server encountered an error while trying to process the request. You could retry the same request following the requirements listed in Timeout (see row above). If the error persists, please report the problem in the android-gcm group.",nil];

    formulaArray = [NSArray arrayWithObjects:@"Implement exponential back-off in your retry mechanism. (e.g. if you waited one second before the first retry,Implement exponential back-off in your retry mechanism. (e.g. if you waited one second before the first retry,Implement exponential back-off in your retry mechanism. (e.g. if you waited one second before the first retry,Implement exponential back-off in your retry mechanism. (e.g. if you waited one second before the first retry,finally",nil];

    self.view.backgroundColor = [UIColor darkGrayColor];
    MaintableView = [[UITableView alloc]init];
    MaintableView.translatesAutoresizingMaskIntoConstraints = NO;
    MaintableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    MaintableView.dataSource=self;
    MaintableView.delegate=self;
    MaintableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [MaintableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    MaintableView.separatorColor = [UIColor blackColor];
    [self.view addSubview:MaintableView];

    NSDictionary * views = NSDictionaryOfVariableBindings(MaintableView);

    NSArray * horizentalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[MaintableView]-0-|" options:0 metrics:nil views:views];

    NSArray * verticalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[MaintableView]-50-|"options:0 metrics:nil views:views];

    [self.view addConstraints:horizentalConstraint];
    [self.view addConstraints:verticalConstraint];

}

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

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [mainArray count];
}

- (UIFont *)fontForCell
{
    return [UIFont fontWithName:@"Bitter-Regular" size:15.0f];
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";

    UITableViewCell *cell =
    [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    if([indexPath section] == 0)
    {

        //Labels adding on cell

        firstLabel = [[UILabel alloc]init];
        firstLabel.textAlignment = NSTextAlignmentLeft;
        firstLabel.text = @"label1";
        firstLabel.font = [UIFont fontWithName:@"Bitter-Regular" size:15.0f];
        firstLabel.translatesAutoresizingMaskIntoConstraints = NO;
        firstLabel.textColor = [UIColor blackColor];
        [cell.contentView addSubview:firstLabel];

        secondLabel = [[UILabel alloc]init];
        secondLabel.textAlignment = NSTextAlignmentLeft;
        secondLabel.text = @"label2";
        secondLabel.font = [UIFont fontWithName:@"Bitter-Regular" size:15.0f];
        secondLabel.translatesAutoresizingMaskIntoConstraints = NO;
        secondLabel.textColor = [UIColor blackColor];
        [cell.contentView addSubview:secondLabel];

        //TextFields adding on cell
        firstName = [[UITextField alloc]init];
        firstName.font = [UIFont fontWithName:@"Bitter-Regular" size:15.0f];
        firstName.translatesAutoresizingMaskIntoConstraints = NO;
        firstName.textColor = [UIColor whiteColor];
        firstName.backgroundColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:firstName];

        secondName = [[UITextField alloc]init];
        secondName.font = [UIFont fontWithName:@"Bitter-Regular" size:15.0f];
        secondName.translatesAutoresizingMaskIntoConstraints = NO;
        secondName.textColor = [UIColor whiteColor];
        secondName.backgroundColor = [UIColor lightGrayColor];
        [cell.contentView addSubview:secondName];


        NSDictionary * views = NSDictionaryOfVariableBindings(firstLabel,secondLabel,firstName,secondName);


        //Applying autolayouts for Labels
        NSArray * firstLabelH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[firstLabel]-10-|"
                                                                                  options:0
                                                                                  metrics:nil
                                                                          views:views];

        NSArray * secondLabelH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[secondLabel]-10-|"
                                                                                                 options:0
                                                                                                 metrics:nil
                                                                           views:views];

        NSArray * firstLabelV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-7-[firstLabel(25)]-|"options:0 metrics:nil views:views];

        NSArray * secondLabelV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-90-[secondLabel(25)]-|"options:0 metrics:nil views:views];


        //Applying autolayouts for textfields
        NSArray * firstNameH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[firstName]-10-|"
                                                                        options:0
                                                                        metrics:nil
                                                                          views:views];

        NSArray * secondNameH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[secondName]-10-|"
                                                                         options:0
                                                                         metrics:nil
                                                                           views:views];

        NSArray * firstNameV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-35-[firstName(30)]-|"options:0 metrics:nil views:views];

        NSArray * secondNameV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-117-[secondName(30)]-|"options:0 metrics:nil views:views];

        //Adding labels
         [cell.contentView addConstraints:firstLabelH];
         [cell.contentView addConstraints:firstLabelV];
         [cell.contentView addConstraints:secondLabelH];
         [cell.contentView addConstraints:secondLabelV];

        //Adding textFields
        [cell.contentView addConstraints:firstNameH];
        [cell.contentView addConstraints:firstNameV];
        [cell.contentView addConstraints:secondNameH];
        [cell.contentView addConstraints:secondNameV];
    }

    if(indexPath.section == 1)
    {

        formulaText = [[UITextView alloc]init];
        formulaText.font = [UIFont fontWithName:@"Bitter-Regular" size:15.0f];
        formulaText.translatesAutoresizingMaskIntoConstraints = NO;
        formulaText.backgroundColor = [UIColor lightGrayColor];
        formulaText.scrollEnabled = NO;
        [cell.contentView addSubview:formulaText];

        NSDictionary * views = NSDictionaryOfVariableBindings(formulaText);

        NSArray * formulaH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[formulaText]-10-|"
                                                                        options:0
                                                                        metrics:nil
                                                                          views:views];

        NSArray * formulaV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[formulaText]-5-|"
                                                                     options:0
                                                                     metrics:nil
                                                                       views:views];

        [cell.contentView addConstraints:formulaH];
        [cell.contentView addConstraints:formulaV];


        formulaText.text = [formulaArray objectAtIndex:0];
        formulaText.font = [UIFont fontWithName:@"Bitter-Regular" size:15.0];

    }

    if (indexPath.section == 2)
    {
        aboutText = [[UITextView alloc]init];
        aboutText.font = [UIFont fontWithName:@"Bitter-Regular" size:15.0f];
        aboutText.translatesAutoresizingMaskIntoConstraints = NO;
        aboutText.backgroundColor = [UIColor darkGrayColor];
        aboutText.scrollEnabled = NO;
        [cell.contentView addSubview:aboutText];

        NSDictionary * views = NSDictionaryOfVariableBindings(aboutText);

        NSArray * formulaH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[aboutText]-10-|"
                                                                     options:0
                                                                     metrics:nil
                                                                       views:views];

        NSArray * formulaV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[aboutText]-5-|"
                                                                     options:0
                                                                     metrics:nil
                                                                       views:views];

        [cell.contentView addConstraints:formulaH];
        [cell.contentView addConstraints:formulaV];

        aboutText.text = [aboutArray objectAtIndex:0];
        aboutText.font = [UIFont fontWithName:@"Bitter-Regular" size:15.0];

    }

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //return 200;

    if([indexPath section] == 0)
    {
        return  200;
    }

    else if([indexPath section] == 1)
    {
        NSString *cellText = [formulaArray objectAtIndex:0];
        UIFont *cellFont = [self fontForCell];
        CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
        CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
        return labelSize.height + 20;
    }

    else
    {
        NSString *cellText = [aboutArray objectAtIndex:0];
        UIFont *cellFont = [self fontForCell];
        CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
        CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
        return labelSize.height + 20;
    }

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionHeaderView = [[UIView alloc] initWithFrame:
                                 CGRectMake(0, 0, tableView.frame.size.width, 30.0)];
    sectionHeaderView.backgroundColor = [UIColor cyanColor];

    UILabel * headerLabel = [[UILabel alloc]init];
    headerLabel.textAlignment = NSTextAlignmentCenter;
    [headerLabel setFont:[UIFont fontWithName:@"Verdana" size:20.0]];
    headerLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [sectionHeaderView addSubview:headerLabel];

    NSDictionary * views = NSDictionaryOfVariableBindings(headerLabel);

    NSArray * horizentalConstraint1 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[headerLabel]-10-|" options:0 metrics:nil views:views];

    NSArray * verticalConstraint1 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[headerLabel(25)]-|"options:0 metrics:nil views:views];

    [sectionHeaderView addConstraints:horizentalConstraint1];
    [sectionHeaderView addConstraints:verticalConstraint1];

    switch (section) {

        case 0:
            headerLabel.text = @"Europe";
            return sectionHeaderView;
            break;

        case 1:
            headerLabel.text = @"Asia";
            return sectionHeaderView;
            break;

        case 2:
            headerLabel.text = @"South America";
            return sectionHeaderView;
            break;

        default:
            break;
    }

    return sectionHeaderView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * myImage = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    myImage.backgroundColor = [UIColor blackColor];
    return myImage;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 30.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50.0f;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

@end

但是我想要扣除那个空位,即使在6加也像第二张图像那样帮我一个enter image description here

1 个答案:

答案 0 :(得分:0)

使用xib创建UITableViewCell - 例如ContinentUITableViewCell。在那里设置你的元素并根据需要设置autolayout。在UITableView中注册它,并设置重用标识符。

接下来是将您的heightForRowAtIndexPath方法替换为:

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

}

另外,在viewDidLoad集合self.tableView.estimatedHeight中平均身高(例如200)。