以编程方式中心UIButton

时间:2012-01-18 10:24:20

标签: objective-c ios cocoa-touch ios5 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;
}

2 个答案:

答案 0 :(得分:6)

您对自动调整遮罩的想法是正确的,但您设置错误:

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

第二行会覆盖您在第一行中设置的内容。设置几个标志的正确方法是:

[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin];

答案 1 :(得分:2)

在我回答你的问题之前有一件事:

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

第二句覆盖第一句,您应该使用|运算符,以便应用两种大小调整掩码:

[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin];

要在视图更改大小时保持元素的位置,您需要告诉它不要使用任何大小调整大小的掩码:

[_notMeButton setAutoresizingMask:UIViewAutoresizingNone];

Interface Builder中的等价物是:

IB autoresizing mask applier

我希望它有所帮助