如何以编程方式添加约束以在屏幕的左下角放置标签?

时间:2015-01-22 16:36:53

标签: ios autolayout

我想在屏幕的左下角放置一个标签:所以我添加了以下代码:

    UILabel *versionLabel = [UILabel new];
  versionLabel.text = @"some text";
  versionLabel.textColor = [UIColor whiteColor];
  versionLabel.font = [UIFont systemFontOfSize:10.0];
  [self.view addSubview:versionLabel];
    [versionLabel setTranslatesAutoresizingMaskIntoConstraints:NO];

    NSDictionary *views = NSDictionaryOfVariableBindings(versionLabel);


    [self.view addConstraints:[NSLayoutConstraint
                               constraintsWithVisualFormat:@"H:|-3-[versionLabel]"
                               options:0
                               metrics:nil
                               views:views]];
    [self.view addConstraints:[NSLayoutConstraint
                               constraintsWithVisualFormat:@"V:[versionLabel]-3-|"
                               options:0
                               metrics:nil
                               views:views]];

我的问题是标签始终位于左上角。当我添加约束时,无法在底部移动它。

1 个答案:

答案 0 :(得分:0)

如果您将UITableViewController包装在UIViewController中,您可以根据需要布置标签和表格视图。

#import "WrappingViewController.h"
#import "YourCustomTableViewController.h"

@implementation WrappingViewController {
}

- (void)viewDidLoad {

    // I instantiate this manually, but you could use an outlet from interface builder
    UITableViewController *tableViewController = [YourCustomTableViewController new];
    [self addChildViewController:tableViewController];

    UIView *tableView = tableViewController.view;

    UILabel *label1 = [UILabel new];
    label1.text = @"Some text";
    label1.font = [UIFont systemFontOfSize:10.0];

    label1.translatesAutoresizingMaskIntoConstraints = NO;
    tableView.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addSubview:tableView];
    [self.view addSubview:label1];

    NSDictionary *views = NSDictionaryOfVariableBindings(tableView, label1);

    [self.view addConstraints:
        [NSLayoutConstraint
            constraintsWithVisualFormat:@"H:|[tableView]|" // make the tableview take the whole width
            options:0
            metrics:nil
            views:views]
    ];

    [self.view addConstraints:
        [NSLayoutConstraint
            constraintsWithVisualFormat:@"H:|-3-[label1]" // attach the label 3 pixels from the left
            options:0
            metrics:nil
            views:views]
    ];

    [self.view addConstraints:
        [NSLayoutConstraint
            constraintsWithVisualFormat:@"V:|[tableView]-[label1]-3-|" // attach tableview to top, then space, then label, 3px, then bottom
            options:0
            metrics:nil
            views:views]
    ];
}

@end