如何在UITableView部分页脚中水平居中UIView?

时间:2016-02-02 23:19:52

标签: ios objective-c uitableview

我目前在UITableView部分的页脚中添加向上或向下箭头图像,如下所示:

UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = [UIColor whiteColor];

MoreButton *moreButton = [MoreButton buttonWithType:UIButtonTypeCustom];
moreButton.frame = CGRectMake(0, 0, 60, 22);
moreButton.sectionIndex = section;

if (self.expandedSection == -1){
    [moreButton setImage:[UIImage imageNamed:@"DownArrow.png"] forState:UIControlStateNormal];
}
else {
    if (self.expandedSection == section) {
        [moreButton setImage:[UIImage imageNamed:@"UpArrow.png"] forState:UIControlStateNormal];
    }
    else {
        [moreButton setImage:[UIImage imageNamed:@"DownArrow.png"] forState:UIControlStateNormal];
    }

}

[moreButton addTarget:self action:@selector(moreButtonSelected:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:moreButton];

return view; 

这样可以正常工作,除了它的图像一直位于左侧,而我希望它位于中间位置:

enter image description here

我知道这是因为我给出了框架(CGRectMake(0, 0, 60, 22);)的定位,但我不确定如何设置x坐标使其水平居中,而与屏幕尺寸无关。

1 个答案:

答案 0 :(得分:0)

这一行:

moreButton.frame = CGRectMake(0, 0, 60, 22);

说你希望按钮出现在它的超级视图的原点0,0(超级视图是页脚)。

如果您将其更改为:

moreButton.frame = CGRectMake(200, 0, 60, 22);

它会更接近中间。

要真正做到这一点,您需要使用自动布局。

基于the code from this question,您应该可以执行以下操作:

MoreButton *moreButton = [MoreButton buttonWithType:UIButtonTypeCustom];
moreButton.frame = CGRectMake(0, 0, 60, 22);
moreButton.sectionIndex = section;

[moreButton setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:viewObj];

NSLayoutConstraint* cn = [NSLayoutConstraint constraintWithItem:moreButton
                                                      attribute:NSLayoutAttributeCenterX
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view
                                                      attribute:NSLayoutAttributeCenterX 
                                                     multiplier:1.0
                                                       constant:0];
[self.view addConstraint:cn];

// this centers the Y... not sure if you need it or not
cn = [NSLayoutConstraint constraintWithItem:moreButton 
                                  attribute:NSLayoutAttributeCenterY
                                  relatedBy:NSLayoutRelationEqual 
                                     toItem:self.view
                                  attribute:NSLayoutAttributeCenterY
                                 multiplier:1.0
                                   constant:0];
[self.view addConstraint:cn];
相关问题