我正在尝试将UIButton添加到TableView中,它位于表格视图的右下角,右边是20,底部是20。但是,它最终会将按钮固定在左上角。我做错了什么?
UIButton *goToTop = [UIButton buttonWithType:UIButtonTypeCustom];
[goToTop setImage:redGo forState:UIControlStateNormal];
[goToTop addTarget:self action:@selector(beginCampaign) forControlEvents:UIControlEventTouchUpInside];
[goToTop setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[goToTop.layer setBorderColor:[[UIColor redColor] CGColor]];
[self.tableView addSubview:goToTop];
goToTop.translatesAutoresizingMaskIntoConstraints = NO;
/* Leading space to superview */
NSLayoutConstraint *leftButtonXConstraint = [NSLayoutConstraint
constraintWithItem:goToTop attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:
NSLayoutAttributeLeft multiplier:1.0 constant:20];
/* Top space to superview Y*/
NSLayoutConstraint *leftButtonYConstraint = [NSLayoutConstraint
constraintWithItem:goToTop attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:
NSLayoutAttributeTop multiplier:1.0f constant:20];
/* Fixed width */
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:goToTop
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:60];
/* Fixed Height */
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:goToTop
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:60];
/* 4. Add the constraints to button's superview*/
[self.tableView addConstraints:@[leftButtonXConstraint, leftButtonYConstraint, widthConstraint, heightConstraint]];
我希望如何:
以下是它的显示方式:
答案 0 :(得分:0)
您已将约束设置为表格视图的左上角而不是右下角。 改变这个:
/* Leading space to superview */
NSLayoutConstraint *leftButtonXConstraint = [NSLayoutConstraint
constraintWithItem:goToTop attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:
NSLayoutAttributeLeft multiplier:1.0 constant:20];
/* Top space to superview Y*/
NSLayoutConstraint *leftButtonYConstraint = [NSLayoutConstraint
constraintWithItem:goToTop attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:
NSLayoutAttributeTop multiplier:1.0f constant:20];
对此:
/* Leading space to superview */
NSLayoutConstraint *leftButtonXConstraint = [NSLayoutConstraint
constraintWithItem:goToTop attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:
NSLayoutAttributeRight multiplier:1.0 constant:20];
/* Top space to superview Y*/
NSLayoutConstraint *leftButtonYConstraint = [NSLayoutConstraint
constraintWithItem:goToTop attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:
NSLayoutAttributeBottom multiplier:1.0f constant:20];