我使用以下代码将UIButton和UITableView添加到UIViewController:
self.tableView = ({
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
tableView.translatesAutoresizingMaskIntoConstraints = NO;
tableView.scrollEnabled = NO;
tableView.allowsSelection = NO;
tableView.dataSource = self;
tableView.delegate = self;
tableView;
});
self.refreshButton = ({
UIButton *button = [UIButton new];
button.translatesAutoresizingMaskIntoConstraints = NO;
[button setTitle:@"testtest" forState:UIControlStateNormal];
[button addTarget:self
action:@selector(clickRefreshButton)
forControlEvents:UIControlEventTouchUpInside];
button.titleLabel.numberOfLines = 1;
button.titleLabel.textAlignment = NSTextAlignmentRight;
button.titleLabel.adjustsFontSizeToFitWidth = NO;
button.alpha = 1.0;
button;
});
[self.view addSubview:self.tableView];
[self.view addSubview:self.refreshButton];
CGFloat tableViewUpPadding = 20.0f;
CGFloat navigationBarHeight = self.navigationController.navigationBar.frame.size.height;
CGFloat tabBarHeight = self.tabBarController.tabBar.frame.size.height;
CGFloat buttonOffset = 10.0f;
CGFloat buttonSideLength = 50.0f;
[self.tableView mas_makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.view.mas_top).offset(tableViewUpPadding);
make.bottom.equalTo(self.view.mas_bottom).offset(-tabBarHeight);
make.width.equalTo(self.view.mas_width);
make.left.equalTo(self.view.mas_left);
}];
[self.refreshButton mas_makeConstraints:^(MASConstraintMaker *make){
make.right.equalTo(self.view.mas_right).offset(-buttonOffset);
make.bottom.equalTo(self.view.mas_bottom).offset(-buttonOffset);
make.width.equalTo(@(buttonSideLength));
make.height.equalTo(@(buttonSideLength));
}];
其中我使用砌体进行自动布局。但是,当我运行应用程序时,按钮不会出现,甚至在查看调试区域也没有。有人可以告诉我原因吗?
或者,如果我使用字符串和struts创建按钮,它仍然不会显示:(
CGRect applicationFrame = [UIScreen mainScreen].bounds;
CGFloat screenWidth = CGRectGetWidth(applicationFrame);
CGFloat screenHeight = CGRectGetHeight(applicationFrame);
CGFloat buttonWidth = 40.0f;
CGFloat buttonHeight = 40.0f;
CGFloat spacing = 10.0f;
CGFloat buttonX = screenWidth - buttonWidth - spacing;
CGFloat buttonY = screenHeight - buttonHeight - spacing;
CGRect buttonFrame = CGRectMake(buttonX, buttonY, buttonWidth, buttonHeight);
[self.refreshButton setFrame:buttonFrame];
顺便说一下,我发现如果我想使用自动布局更改self.tableView
的宽度,那么它也是不可能的:
[self.tableView mas_makeConstraints:^(MASConstraintMaker *make){
make.top.equalTo(self.view.mas_top).offset(tableViewUpPadding);
make.bottom.equalTo(self.view.mas_bottom).offset(-tabBarHeight);
make.width.equalTo(self.view.as_width).offset(-offset);
make.left.equalTo(self.view.mas_left);
}];
事实证明,tableview仍然与self.view
一样宽