2012-01-18 105 views
3

我有一個UIButton,我以編程方式添加。這裏沒有問題,因爲它應該和看起來不錯。 但是,當我將手機傾斜到風景時,按鈕不正確,我希望它仍居中。以編程方式中心UIButton

肖像: It's centered here

景觀: Not centered here

我已經嘗試了一堆東西,但似乎無法得到它的工作,在我看來,該自動尺寸應該然而照顧它。 ..在這種情況下它不起作用。

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section 
{ 
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 49)]; 

    _notMeButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    UIImage *butImage = [[UIImage imageNamed:@"notme.png"] stretchableImageWithLeftCapWidth:6 topCapHeight:6]; 
    UIImage *butImagePressed = [[UIImage imageNamed:@"KC_notmePressed.png"] stretchableImageWithLeftCapWidth:6 topCapHeight:6]; 
    [_notMeButton setBackgroundImage:butImage forState:UIControlStateNormal]; 
    [_notMeButton setBackgroundImage:butImagePressed forState:UIControlStateHighlighted]; 
    [_notMeButton setTitle:NSLocalizedString(@"Change address", @"KlarnaCheckout") forState:UIControlStateNormal]; 
    [_notMeButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal]; 
    [_notMeButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted]; 
    [_notMeButton setTitleShadowColor:[UIColor whiteColor] forState:UIControlStateNormal]; 
    [_notMeButton.titleLabel setShadowColor:[UIColor whiteColor]]; 
    [_notMeButton.titleLabel setShadowOffset:CGSizeMake(0, 1)]; 
    [_notMeButton.titleLabel setFont:[UIFont systemFontOfSize:14]]; 
    [_notMeButton addTarget:self action:@selector(thisIsNotMe) forControlEvents:UIControlEventTouchUpInside]; 
    [_notMeButton setTag:1]; 
    [_notMeButton sizeToFit]; 
    [_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; 
    [_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin]; 
    [_notMeButton setFrame:CGRectMake(10, 10, _notMeButton.frame.size.width+20, _notMeButton.frame.size.height)]; 
    [_notMeButton setCenter:footerView.center]; 

    [footerView addSubview:_notMeButton]; 

    return footerView; 
} 

回答

6

您對自動調整面膜的想法是對的,但你正確設置它:

[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; 
[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin]; 

第二行覆蓋了你在第1套。設置多個標誌正確的方法是:

[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin]; 
2

一件事之前,我回答你的問題:

[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; 
[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin]; 

第二句覆蓋第一個,你應該使用|運營商這樣既調整掩碼適用於:

[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin]; 

要保持元素的地方是當視圖改變其大小,你需要告訴它不使用任何調整面膜:

[_notMeButton setAutoresizingMask:UIViewAutoresizingNone]; 

而且在Interface Builder中相當於是這樣的:

IB autoresizing mask applier

我希望它能幫助

相關問題