【问题标题】:How do i make my picture relocate it self on the screen with a button如何使用按钮使我的图片在屏幕上自行重新定位
【发布时间】:2013-03-27 06:44:25
【问题描述】:

我正在学习 Xcode,我想知道如何让按钮刷新我的代码或其他内容的一部分。我将图片放在屏幕上的随机位置,但我希望能够按下按钮将其重新定位到另一个随机位置,任何输入将不胜感激。谢谢。这是我的代码。视图控制器.m

- (void)viewDidLoad
{
int xValue = arc4random() % 320;
int yValue = arc4random() % 480;


UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(xValue, yValue, 70, 30)];
NSString *imgFilepath = [[NSBundle mainBundle] pathForResource:@"clubs-2-150" ofType:@"jpg"];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:imgFilepath];
[imgView setImage:img];
[self.view addSubview:imgView];


[super viewDidLoad];   
}

【问题讨论】:

    标签: ios objective-c button user-interface


    【解决方案1】:

    就目前的代码而言,变量不可能有范围,也就是说,它们只存在于某些函数或类中。你的变量imgView 只存在于viewDidLoad。为了让您能够在其他地方访问它,您需要将其声明为实例变量。

    在你的 .h 文件中:

    @interface yourClassName : UIViewController {
       UIImage *imageIWantToChange;
    } 
    

    这将允许您在所有 yourClassName 函数中访问 imageIWantToChange。

    现在,在你的 .m 上

    - (void)viewDidLoad
    {
    
       [super viewDidLoad];   
    
       int xValue = arc4random() % 320;
       int yValue = arc4random() % 480;
    
       //Notice that we do not have UIImage before imageIWantToChange
       imageIWantToChange = [[UIImageView alloc] initWithFrame:CGRectMake(xValue, yValue, 70, 30)];
       UIImage *img = [UIImage imageNamed:@"clubs-2-150.jpg"];
       [imageIWantToChange setImage:img];
       [self.view addSubview:imgView];
    
    }
    

    然后在您的 IBAction 或按钮选择器中:

    -(IBAction) buttonWasPressed:(id) sender {
       CGRect frame = imageIWantToChange.frame;
    
       frame.origin.x = arc4random() % 320;
       frame.origin.y = arc4random() % 480;
    
       imageIWantToChange.frame = frame;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 2020-04-04
      • 1970-01-01
      相关资源
      最近更新 更多