如何通过代码而非故事板更改UIButton大小和位置

时间:2016-09-11 01:29:46

标签: ios swift uiview size uistoryboard

我一直在试图通过代码改变故事板场景中按钮的大小,但每次加载场景时按钮大小都保持不变。我已经尝试在视图加载时更改按钮的框架大小,我也尝试通过CGRect更改框架,但它们似乎都没有工作。例如:

clickerbutton.frame = CGRect(x: 100, y: 100, width: 1000, height: 1000)

 clickerbutton.frame.size = CGSize(width: 100, height: 100)

2 个答案:

答案 0 :(得分:2)

确保您没有使用 AutoLayout ,因为使用autoLayout不允许您修改按钮大小

尝试使用: -

 let dummyBtn : UIButton = UIButton() 

  override func viewDidLoad() {

    super.viewDidLoad()
    dummyBtn.frame = CGRect(x: 100, y: 100, width: 200, height: 150)
    dummyBtn.layer.backgroundColor = UIColor.blackColor().CGColor
    self.view.addSubview(dummyBtn)
    print(dummyBtn.frame)

}

func someFunction(){
  dummyBtn.frame = CGRectMake(x: 10, y: 10, width: 1000, height: 1000)
     }

答案 1 :(得分:0)

以编程方式布局按钮:

为按钮的每个约束添加IBOutlets并在代码中更改它们。

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myButtonTopSpaceConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myButtonLeadingSpaceConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myButtonWidthConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *myButtonHeightConstraint;

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

    self.myButtonLeadingSpaceConstraint.constant = 10;
    self.myButtonTopSpaceConstraint.constant =  20;
    self.myButtonWidthConstraint.constant = 200;
    self.myButtonHeightConstraint.constant = 70;

}

使用以下GitHub链接下载示例项目:

https://github.com/k-sathireddy/ButtonCustomLayout

如果你想要没有约束:

以编程方式创建按钮,然后根据需要更改框架。