【问题标题】:Moving a UIImageView with a UIButton使用 UIButton 移动 UIImageView
【发布时间】:2015-01-28 22:31:54
【问题描述】:

我对 Xcode 和 iOS 开发相当陌生,但到目前为止我一直很享受挑战。

我遇到了一个问题,我试图移动一个UIImageView 我以编程方式在 MapBox 地图视图之上创建。

我想将这个UIImageViewUIButton 移动一个像素,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

【问题讨论】:

    标签: ios uiimageview uibutton mapbox


    【解决方案1】:

    一个问题是 ship 是您在第一个代码块中创建的局部变量。当该代码块超出范围时,ship 将为零,因此当您尝试在按钮方法中设置它的中心时,它将不起作用。您需要为 ship 创建一个属性,然后使用它。

    您的另一个问题是,当您将操作添加到按钮时,您将其称为 buttonPressed:,但您实现的方法是 moveUp。因此,如果您创建一个名为 ship 的属性,那么您的操作方法应该是,

    - (void)buttonPressed:(UIButton *) sender {
        self.ship.center = CGPointMake(self.ship.center.x, self.ship.center.y -10);
    }
    

    【讨论】:

    • @MorganJones,如果这个答案解决了你的问题,你应该接受它。
    猜你喜欢
    • 2013-01-08
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 2013-04-24
    • 2012-04-21
    • 2023-03-20
    相关资源
    最近更新 更多