【问题标题】:How to move UIButton programmatically. Objective-C Xcode如何以编程方式移动 UIButton。 Objective-C Xcode
【发布时间】:2012-11-27 16:59:40
【问题描述】:

我看到了一些解决方案,但都没有解决我的问题。

我有一个 UIButton,只需在 Storyboard 编辑器中拖放到 UIViewController 即可。

UIButton 有一个链接到与该视图关联的UIViewController 的.h 文件的出口。它也在.m 文件中合成。

@property (strong, nonatomic) IBOutlet UIButton *answerButton;

我想像这样在运行时更改按钮的位置;

CGRect btFrame = answerButton.frame;
btFrame.origin.x = xOne;
btFrame.origin.y = yOne;
answerButton.frame = btFrame;

但是,每当我尝试此操作时,按钮都会拒绝移动。

所有其他编辑功能(如setTitle 等)都可以正常工作,但由于某种原因,框架不会按我想要的方式移动。

【问题讨论】:

  • 使用手势功能
  • 你在使用自动布局吗?
  • @Vikas,用户没有移动按钮。按钮的位置由他们之前所做的一些选择决定。 xOne, yOne 是 2 个 int 值,创建一个基于先前所做选择而更改的点。我只是希望能够将框架设置为这些已知的 int 值。
  • @SamBo 确保您没有在情节提要中启用自动布局。 See this answer 如果您需要帮助确定它是否已启用并将其关闭。
  • 成功了!非常感谢 Rob 和 Zaphod!

标签: ios objective-c xcode uibutton


【解决方案1】:

只需在文件检查器中取消选中“使用自动布局”即可..

【讨论】:

    【解决方案2】:

    .h 文件

        #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController{
        IBOutlet UIButton *theButton;
    }
    @property(nonatomic, strong) IBOutlet UIButton *theButton;
    -(IBAction)moveTheButton:(id)sender;
    
    @end
    

    .m 文件

    -(IBAction)moveTheButton:(id)sender{
    CGRect btFrame = theButton.frame;
    btFrame.origin.x = 90;
    btFrame.origin.y = 150;
    theButton.frame = btFrame;
    

    }

    此代码将按钮从一个点移动到另一个点。

    【讨论】:

      【解决方案3】:

      用以下代码替换您的代码,其中包括删除自动调整大小掩码的代码。

      CGRect btFrame = answerButton.frame;
      btFrame.origin.x = xOne;
      btFrame.origin.y = yOne;
      answerButton.autoresizingMask = UIViewAutoresizingNone;
      answerButton.frame = btFrame;
      

      【讨论】:

      • 你 NSLog xOne, yOne 并检查它是什么?
      猜你喜欢
      • 2016-09-28
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多