ios 点击时更改 UIView/UIControl 的屏幕位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4742744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing screen position of UIView/UIControl upon tapping it
提问by James Dunay
I'm well aware this is a simple question. I would like to learn how to move a CGRect/UIButton to a different spot on the screen when the user selects it. Thanks for your help in advance.
我很清楚这是一个简单的问题。我想了解如何在用户选择时将 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{
???
}
回答by Gianz
I think you need to add a :
in the @selector(buttonClicked:)
statement since IBAction
s expect a single (id)sender
method attribute.
我认为您需要:
在@selector(buttonClicked:)
语句中添加 a ,因为IBAction
s 需要单个(id)sender
方法属性。
You can do something similar to the code below.
您可以执行类似于以下代码的操作。
- (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;
}
If you want to animate it, you can add the beginAnimation block.
如果要为其设置动画,可以添加 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];
}
回答by user2083364
CGRectOffset(rect, dx, dy)
CGRectOffset(rect, dx, dy)
Moves the origin of the rect by the delta X and Y.
将矩形的原点移动 delta X 和 Y。