如何在Objective-C Xcode中编程移动UIButton。

11

我看过一些解决方案,但都没能解决我的问题。

我有一个通过在Storyboard编辑器中简单拖放到UIViewController中创建的UIButton

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 S Singh
3
你正在使用自动布局吗? - Zaphod
@Vikas,用户没有移动按钮。按钮的位置是由他们之前做出的一些选择确定的。xOne、yOne是两个整数值,创建了一个点,该点根据之前所做的选择而改变。我只想能够将框架设置为这些已知的整数值。 - SamBo
@SamBo 确保你的故事板中没有启用自动布局。如果需要帮助确定是否启用并关闭它,请参阅此答案:https://dev59.com/GWYs5IYBdhLWcg3wBvb7#13201690。 - rob mayoff
成功了!非常感谢 Rob 和 Zaphod! - SamBo
3个回答

19

在文件检查器中取消勾选"使用自动布局"即可。


7

.h file

    #import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    IBOutlet UIButton *theButton;
}
@property(nonatomic, strong) IBOutlet UIButton *theButton;
-(IBAction)moveTheButton:(id)sender;

@end

.m file

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

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


4
请使用以下代码替换您的代码,其中包括删除自动调整大小掩码的代码。
CGRect btFrame = answerButton.frame;
btFrame.origin.x = xOne;
btFrame.origin.y = yOne;
answerButton.autoresizingMask = UIViewAutoresizingNone;
answerButton.frame = btFrame;

你有没有NSLog xOne,yOne并检查它是什么? - Paramasivan Samuttiram

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接