以编程方式中心UIButton
我有一个UIButton,我以编程方式添加。 这里没有问题,它应该像它应该和看起来不错。 然而,当我倾斜手机风景的button不正确,我希望它仍然居中。
肖像:
景观:
我已经尝试了一堆东西,但似乎无法得到它的工作,在我看来,autoresizing应该照顾它,但是…它不起作用的情况下。
- (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; }
你关于自动调整掩码的想法是正确的,但你设置不正确:
[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; [_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin];
第二行覆盖你在第一次设置的内容。 正确的方法来设置几个标志将是:
[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin];
有一件事我回答你的问题之前:
[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; [_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin];
第二个句子覆盖第一个,你应该使用|
运算符,所以这两个resize面具应用:
[_notMeButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin];
为了使元素保持在视图改变大小的位置,你需要告诉它不要使用任何resize的掩码:
[_notMeButton setAutoresizingMask:UIViewAutoresizingNone];
而Interface Builder中的等价物是这样的:
我希望它有帮助