2016-02-02 47 views
-1

我目前加入任何一個在我UITableView節的頁腳向上或向下箭頭的圖像,像這樣:如何在UITableView部分頁腳中水平居中放置UIView?

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座標有無論屏幕大小如何,它都是水平居中的。

回答

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];