使用 UIButton 移动 UIImageView
Moving a UIImageView with a UIButton
我是 Xcode 和 iOS 开发的新手,但到目前为止我一直在享受挑战。
我 运行 遇到一个问题,我试图移动 UIImageView
我在 MapBox mapView 之上以编程方式创建的。
我想用 UIButton
将此 UIImageView
移动一个像素,UIButton 位于 mapView 的顶部。
这是我目前在 ViewController.m:
中的代码
[self.view addSubview:mapView];
UIImageView* ship;
ship=[[UIImageView alloc] initWithFrame:CGRectMake(150, 200, 40, 40)];
UIImage * image;
image=[UIImage imageNamed:@"spaceShip"];
[ship setImage:image];
ship.alpha = 0.75;
[self.view addSubview:ship];
UIButton *upButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
upButton.frame = CGRectMake(150, 250, 40, 40);
upButton.userInteractionEnabled = YES;
[upButton setTitle:@"UP" forState:UIControlStateNormal];
[upButton addTarget:ship action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:upButton];
}
- (IBAction)moveUp {
ship.center = CGPointMake(ship.center.x, ship.center.y -10);
}
谁能告诉我如何让这个 upButton 识别和移动我的 UIImageView
?
一个问题是 ship 是您在第一个代码块中创建的局部变量。当该代码块超出范围时,ship 将为 nil,因此当您尝试在按钮方法中将其设置为中心时,它将不起作用。您需要为 ship 创建一个 属性,然后使用它。
您的另一个问题是,当您将动作添加到您的按钮时,您将其称为buttonPressed:,但您实现的方法是moveUp。所以,如果你创建一个名为 ship 的 属性,那么你的操作方法应该是,
- (void)buttonPressed:(UIButton *) sender {
self.ship.center = CGPointMake(self.ship.center.x, self.ship.center.y -10);
}
我是 Xcode 和 iOS 开发的新手,但到目前为止我一直在享受挑战。
我 运行 遇到一个问题,我试图移动 UIImageView
我在 MapBox mapView 之上以编程方式创建的。
我想用 UIButton
将此 UIImageView
移动一个像素,UIButton 位于 mapView 的顶部。
这是我目前在 ViewController.m:
中的代码 [self.view addSubview:mapView];
UIImageView* ship;
ship=[[UIImageView alloc] initWithFrame:CGRectMake(150, 200, 40, 40)];
UIImage * image;
image=[UIImage imageNamed:@"spaceShip"];
[ship setImage:image];
ship.alpha = 0.75;
[self.view addSubview:ship];
UIButton *upButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
upButton.frame = CGRectMake(150, 250, 40, 40);
upButton.userInteractionEnabled = YES;
[upButton setTitle:@"UP" forState:UIControlStateNormal];
[upButton addTarget:ship action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:upButton];
}
- (IBAction)moveUp {
ship.center = CGPointMake(ship.center.x, ship.center.y -10);
}
谁能告诉我如何让这个 upButton 识别和移动我的 UIImageView
?
一个问题是 ship 是您在第一个代码块中创建的局部变量。当该代码块超出范围时,ship 将为 nil,因此当您尝试在按钮方法中将其设置为中心时,它将不起作用。您需要为 ship 创建一个 属性,然后使用它。
您的另一个问题是,当您将动作添加到您的按钮时,您将其称为buttonPressed:,但您实现的方法是moveUp。所以,如果你创建一个名为 ship 的 属性,那么你的操作方法应该是,
- (void)buttonPressed:(UIButton *) sender {
self.ship.center = CGPointMake(self.ship.center.x, self.ship.center.y -10);
}