首先,您似乎没有正确设置按钮的矩形。请记住,第三个参数是宽度:
CG_INLINE CGRect
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
CGRect rect;
rect.origin.x = x; rect.origin.y = y;
rect.size.width = width; rect.size.height = height;
return rect;
}
在button.frame = CGRectMake(80.0, 210.0, 40.0, 160.0);
您将按钮的宽度设置为 40。
更重要的是,您应该使用字符串和 struts,甚至更好的自动布局。当您让计算机进行数学运算时,生活会轻松得多。只需要一个按钮,springs 和 struts 就足够了,但是如果你想创建一个更灵活的界面,并且你可以针对 iOS 6,那么你应该使用 autolayout。
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
[button setTranslatesAutoresizingMaskIntoConstraints:NO];
[[self view] addSubview:button];
NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:button
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationGreaterThanOrEqual
toItem:nil
attribute:NSLayoutAttributeWidth
multiplier:1
constant:200];
[button addConstraint:widthConstraint];
NSLayoutConstraint *bottomContraint = [NSLayoutConstraint constraintWithItem:button
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:[self view]
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:-20];
NSLayoutConstraint *centerContraint = [NSLayoutConstraint constraintWithItem:button
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:[self view]
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:0];
NSArray *constraints = [[NSArray alloc] initWithObjects:bottomContraint, centerContraint, nil];
[[self view] addConstraints:constraints];
如果你想使用弹簧和支柱,你必须设置自动调整掩码:
[button setAutoresizingMask:(UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin)];
这两件事在 Interface Builder 中要容易得多。