UIButton位置变化

8
我在IB中设置了一个按钮,并创建了一个IBOutlet,并将屏幕对象链接到它。是否有办法通过编程方式更改该按钮的位置和/或大小?我知道您可以更改标题和一些其他内容,但我不知道如何更改其位置或大小。
现在我想相应地更改它的位置。这是可能的吗?如果是,请告诉我如何操作,因为我正在尝试在头文件中更改按钮的位置,但这在代码中无效。
@property (nonatomic, strong) IBOutlet UIButton *mybuttonOutlet;

在实现文件中:
-(void)viewDidLoad {


    screenSizeHeight=[UIScreen mainScreen].bounds.size.height;


if(screenSizeHeight==568)

    mybuttonOutlet.frame= CGRect(38, 464 ,157,25);


if(screenSizeHeight==480)

    mybuttonOutlet.frame= CGRect(38, 364 ,157,25);

}

你是否将这个 myButtonOutlet 与你的 .xib 文件连接了? - Thilina Chamath Hewagama
我找不到任何原因,为什么这个不起作用,除非你忘记连接IBOutlet。 - Anupdas
是的,我已经将我的按钮连接到了我的.xib文件。 - casillas
你瞎猜的,是不是把多个插座连接到同一个按钮了? - Anupdas
我的按钮只有一个插口。 - casillas
6个回答

14

从IB或Storyboard中的按钮中删除使用自动布局


我相信你只能从整个xib/SB中删除自动布局 - 这对我也起作用了。 - kraftydevil

5
如果您想在启用自动布局的情况下调整位置,则需要按照以下方式更改代码。
-(void)viewDidLayoutSubviews {

    screenSizeHeight=[UIScreen mainScreen].bounds.size.height;

    if(screenSizeHeight==568)
        mybuttonOutlet.frame= CGRect(38, 464 ,157,25);

    if(screenSizeHeight==480)
        mybuttonOutlet.frame= CGRect(38, 364 ,157,25);
}

基本上,如果启用了自动布局,则需要在viewDidLayoutSubviews方法中执行任何自定义布局调整。

0
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end


#import "ViewController.h"

@interface ViewController ()
@property(nonatomic, strong) IBOutlet UIButton *theButton;


// -(IBAction)moveTheButton:(id)sender;

@end

@implementation ViewController
@synthesize theButton;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)moveTheButton:(id)sender{
    //set default position
    CGRect btFrame = theButton.frame;
    btFrame.origin.x = 145;
    btFrame.origin.y = 285;
    theButton.frame = btFrame;

    //position changing
    btFrame.origin.x += 40;
    theButton.frame = btFrame;

    //new size of button
    CGRect rect=CGRectMake(145, 285, 190, 30);
    [self.theButton setBounds:rect];

}

@end

0
我想到的解决方法是在主视图中创建新的视图对象,并将我的“动态变化的对象”放入该视图中(如图所示)。 对象层次结构 然后,我使用自动布局来定位主视图中的新视图。但是,位于新视图内部的bugButton:UIButton会随着以下预期的位置发生变化:
bugButton.frame.origin = CGPoint(x: newX, y: newY)

0
请执行这个检查。
-(void)viewDidLoad{
    if(self.mybuttonOutlet==nil)NSLog(@"Button is NIL");
}

如果你看到日志信息“Button is NIL”,那么很可能是因为你忘记将IB按钮链接到变量mybuttonOutlet了。


0
最终我选择了使用约束。获取确定按钮位置(顶部、底部、前导和尾随)的约束点,并更改约束值。
self.constBtnSubmitTrailing.constraint = 50.0

这样你就可以保持AutoLayout的启用状态。


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