在点击它时更改UIView/UIControl的屏幕位置

Jam*_*nay 4 cocoa-touch objective-c uiview ios

我很清楚这是一个简单的问题.我想学习如何在用户选择CGRect/UIButton时将其移动到屏幕上的其他位置.感谢您的帮助.

- (void)showMeSomeButtons:(CGRect)frame{

    button = [[UIButton alloc] initWithFrame:frame];
    button.frame = CGRectMake(240, 150, 50, 50);

    UIImage *buttonGraphic = [UIImage imageNamed:@"1.png"];

    [button setBackgroundImage:buttonGraphic forState:UIControlStateNormal];
    [button addTarget:self.viewController action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

    [self addSubview:button];
}

-(void)buttonClicked{

    ???
}
Run Code Online (Sandbox Code Playgroud)

小智 14

我认为你需要:@selector(buttonClicked:)语句中添加一个,因为IBActions期望一个(id)sender方法属性.

您可以执行与以下代码类似的操作.

- (void)buttonClicked:(id)sender {
   CGRect frame = button.frame;
   frame.origin.x = 500; // new x coordinate
   frame.origin.y = 500; // new y coordinate
   button.frame = frame;
}
Run Code Online (Sandbox Code Playgroud)

如果要为其设置动画,可以添加beginAnimation块.

- (void)buttonClicked:(id)sender {
    CGRect frame = button.frame;
    frame.origin.x = 500; // new x coordinate
    frame.origin.y = 500; // new y coordinate

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration: 0.25];
    button.frame = frame;
    [UIView commitAnimations];
 }
Run Code Online (Sandbox Code Playgroud)