这是一个非常简单(可能很愚蠢)的问题,但我似乎找不到最干净和最好的方法。我有三个按钮,在纵向模式下看起来不错。我还可以通过添加 autoResizingMasks 来使中心始终居中:
[self.centerButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin];
但是,我不确定处理左右按钮的最佳方式。见下图;我需要的是让他们稍微移动一下,在中间和左/右边缘之间居中:
对于这个可能愚蠢的问题,我很抱歉,因为我确信这可以通过 IB 或(最好)代码相当容易地完成,但我只是想了解正确和最干净的方法。提前致谢!
编辑
一些附加信息,我正在使用 iPad,底部的按钮实际上包含在底部的一个名为“buttonPanel”的子视图中。
根据其中一个答案的建议,我添加了以下代码;见下文。但是,我只得到“无法同时满足约束”。添加此代码时出错,并且当它列出约束时,它只列出下面的那些,因此此视图上没有其他附加约束。下面的代码有问题吗?担心我在这里遗漏了一些明显的东西..
- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.buttonPanel removeConstraint:conLeft];
[self.buttonPanel removeConstraint:conRight];
float paddingPortrait = 20; // pd
float paddingLandscape = 50; // ld
float widthOfView = 768;
float heightOfView = 249;
float denominatorVal = heightOfView - widthOfView;
float leftMultiplier = (paddingLandscape - paddingPortrait) / denominatorVal;
float rightMultiplier = (denominatorVal + paddingPortrait - paddingLandscape) / denominatorVal;
float leftConstant = paddingPortrait - (widthOfView * leftMultiplier);
float rightConstant = -leftConstant;
conLeft = [NSLayoutConstraint constraintWithItem:self.leftButton attribute:NSLayoutAttributeLeading relatedBy:0 toItem:self.buttonPanel attribute:NSLayoutAttributeRight multiplier:leftMultiplier constant:leftConstant];
conRight = [NSLayoutConstraint constraintWithItem:self.rightButton attribute:NSLayoutAttributeTrailing relatedBy:0 toItem:self.buttonPanel attribute:NSLayoutAttributeRight multiplier:rightMultiplier constant:rightConstant];
[self.buttonPanel addConstraints:@[conRight,conLeft]];
}
这是抛出的错误:
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
"(NSAutoresizingMaskLayoutConstraint:0x8b36ce0 h=&-& v=&-- H:[UIButton:0x8874200(166)])",
"(NSAutoresizingMaskLayoutConstraint:0x8b38720 h=&-& v=&-- H:[UIImageView:0x8877880(200)])",
"(NSAutoresizingMaskLayoutConstraint:0x8b38640 h=&-& v=&-- UIImageView:0x8877880.midX == 0.165365*UIView:0x8876c00.width)",
"(NSLayoutConstraint:0x8b3a780 UIImageView:0x8877880.leading == 0.127119*UIView:0x8876c00.right - 77.6271)",
"(NSLayoutConstraint:0x8b3a6a0 UIButton:0x8874200.trailing == 0.872881*UIView:0x8876c00.right + 77.6271)",
"(NSAutoresizingMaskLayoutConstraint:0x8b36ca0 h=&-& v=&-- UIButton:0x8874200.midX == 0.848958*UIView:0x8876c00.width)"
)
将尝试通过打破约束来恢复 (NSLayoutConstraint:0x8b3a6a0 UIButton:0x8874200.trailing == 0.872881*UIView:0x8876c00.right + 77.6271)