我有一件奇怪的事情,我想说明那件事。 我有一个处于横向模式的视图。由于横向模式,我有一个需要更改框架的按钮:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 40.0, 160.0);
[view addSubview:button];
正常:
button.frame = CGRectMake(80.0,210.0,160.0,40.0);
风景:
button.frame = CGRectMake(80.0,210.0,40.0,160.0);
一切都很好,除了按钮的标题:“SHOW View”
而不是说Show view它说:
w
e
i
V
w
o
h
S
从按钮到顶部阅读:P 这是我的按钮标题,因为它的风景,但标题仍然是肖像。
任何帮助表示赞赏:)
答案 0 :(得分:0)
首先,您似乎没有正确设置按钮的矩形。请记住,第三个参数是宽度:
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,甚至更好的自动布局。当你让计算机进行数学计算时,生活会变得如此简单。只需一个按钮,弹簧和支柱就是您所需要的,但如果您想创建一个更灵活的界面,并且您可以定位iOS 6,那么您应该使用自动布局。
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中这两件事情要容易得多。