如果在addSubView之后调用,则UIButton不会移动

Sco*_*a P 4 iphone uibutton ios

所以我试图UIButton在点击后移动一个.

_addMoreFields单击按钮后调用该方法.

_addMoreFieldBtn是一个全球性的UIButton.当我点击它没有任何反应.

奇怪的是,如果我注释掉addSubView代码,那么按钮会移动.

如果我保留该代码,则按钮不会移动.

有任何想法吗?

-(void)movePlusButton {
    NSLog(@"Moving button");
    [UIButton beginAnimations:nil context:nil];
    [UIButton setAnimationDuration:0.3];
    _addMoreFieldsBtn.center = CGPointMake(30,30);
    [UIButton commitAnimations];
}

- (IBAction)addMoreFields:(id)sender {

    CGRect currentBtnFrame = [(UIButton *)sender frame];
    CGPoint org = currentBtnFrame.origin;

    UILabel *whoWasIn = [[UILabel alloc]  initWithFrame:CGRectMake(110, org.y, 85, 21)];
    whoWasIn.text = @"test";

    UITextField *whoWasInField = [[UITextField alloc] initWithFrame:CGRectMake(59, whoWasIn.frame.origin.y+40, 202, 30)];
    whoWasInField.placeholder = @"test2";

    UILabel *with = [[UILabel alloc]  initWithFrame:CGRectMake(136, whoWasInField.frame.origin.y+40, 49, 21)];
    with.text = @"with";
    whoWasInField.borderStyle = UITextBorderStyleRoundedRect;

    UITextField *withField = [[UITextField alloc] initWithFrame:CGRectMake(59, with.frame.origin.y+40, 202, 30)];
    withField.placeholder = @"test3";
    withField.borderStyle = UITextBorderStyleRoundedRect;

    [_homeView addSubview:whoWasIn];
    [_homeView addSubview:with];
    [_homeView addSubview:whoWasInField];
    [_homeView addSubview:withField];

    [self movePlusButton];
}
Run Code Online (Sandbox Code Playgroud)

注意:我也尝试更改框架,但我遇到了同样的问题.它从我放到现有位置的新位置开始动画.

J S*_*iro 5

问题是iOS 6/Xcode 4.5中的新项目默认启用了"Autolayout".Autolayout是"Springs and Struts"的替代品(但它仅适用于iOS 6).此功能会向视图添加约束,该约束优先于您在代码中尝试的移动.

所以有三种可能的解决方法:

1)以编程方式在按钮上创建新约束.Autolayout非常强大且灵活......特别是如果你想要支持iPhone 5和早期型号的足迹.您可以通过查看WWDC视频找到有关如何执行此操作的更多信息:iOS和OS X的自动布局简介

2)不要使用Autolayout.在Storyboard中选择一个视图,然后在文件检查器中取消选中"使用Autolayout".

3)为按钮上的每个约束创建IBOutlets.然后在移动按钮之前,删除这些约束:

@interface MyViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *addMoreFieldsBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *hConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *vConstraint;
- (IBAction)addMoreFields:(id)sender;
@end
Run Code Online (Sandbox Code Playgroud)

和...

-(void)movePlusButton {
    NSLog(@"Moving button");
    [self.view removeConstraint:self.hConstraint];
    [self.view removeConstraint:self.vConstraint];
    [UIButton beginAnimations:nil context:nil];
    [UIButton setAnimationDuration:0.3];
    _addMoreFieldsBtn.center = CGPointMake(30,30);
    [UIButton commitAnimations];
}
Run Code Online (Sandbox Code Playgroud)

(您需要调用的实际视图removeConstraints:是按钮的父视图,可能是也可能不是self.view).