【问题标题】:Changing screen position of UIView/UIControl upon tapping it通过点击它来改变 UIView/UIControl 的屏幕位置
【发布时间】:2011-01-20 01:50:35
【问题描述】:

我很清楚这是一个简单的问题。我想了解当用户选择它时如何将 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{

    ???
}

【问题讨论】:

    标签: ios objective-c cocoa-touch uiview


    【解决方案1】:

    我认为您需要在@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;
    }
    

    如果你想对其进行动画处理,可以添加 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];
     }
    

    【讨论】:

    • 关于这个的两个问题,当我输入顶部代码时,它告诉我“CGRect 没有名为'x'的成员”,对于“y”也是如此,我是否忘记添加一些东西。这也是一个更基本的问题,但是在顶行中添加的(id)发件人是什么?非常感谢。
    • 糟糕。抱歉,刚刚更新了我的答案。其实就是frame.origin.x。
    • 根据docs IBAction 有以下要求:“[…] 返回类型为 void。签名的其余必需部分是单个参数,类型为 id 并命名(按约定)发件人。”所以冒号 not 是可选的。相应地编辑了您的答案。希望你不要介意。
    【解决方案2】:

    CGRectOffset(rect, dx, dy)

    将矩形的原点移动 delta X 和 Y。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-26
      • 2022-10-06
      相关资源
      最近更新 更多