移动程序生成的按钮



我有一个以编程方式创建的按钮,当调用特定方法时,我想将其移动到不同的位置。到目前为止,我可以看到我创建的按钮,并且我可以移动我拖放到情节提要中的不同按钮,但我不确定如何在代码中引用程序生成的按钮来更改其位置。

生成按钮的代码:

UIButton *generatedButton = [UIButton buttonWithType:UIButtonTypeCustom];
[generatedButton addTarget:self
                    action:@selector(genButtonTouched:)
          forControlEvents:UIControlEventTouchDown];
generatedButton.frame = CGRectMake(84.0, 80.0, 70.0, 40.0);
[self.view addSubview:generatedButton];

在另一个方法中,我有用于更改按钮位置的代码。如果这个代码与我生成按钮的方法相同,它可以正常工作,但我需要将其放在不同的方法中:

[generatedButton setFrame:CGRectMake(xCoord, yCoord, buttonWidth, buttonHeight)];

在您的ButtonViewController.h 中

@interface ButtonViewController : UIViewController{
    }
@property (retain, nonatomic) UIButton *generatedButton;

在您的ButtonViewController.m 中

@implementation ButtonViewController
@synthesize generatedButton;
- (void)viewDidLoad
{
generatedButton = [UIButton buttonWithType:UIButtonTypeCustom];
[generatedButton addTarget:self
                    action:@selector(genButtonTouched:)
          forControlEvents:UIControlEventTouchDown];
generatedButton.frame = CGRectMake(84.0, 80.0, 70.0, 40.0);
[self.view addSubview:generatedButton];
}

//要在类中的任何位置调用按钮,请执行以下操作:-

-(void)methodToMoveButton{
[generatedButton setFrame:CGRectMake(xCoord, yCoord, buttonWidth, buttonHeight)];
}

如果你想要别的,请告诉我。

这与移动故事板中添加的按钮没有什么不同。创建一个实例变量来保存对您生成的按钮的引用。然后,您可以使用该实例变量访问另一个方法中的按钮。

最新更新