Swift - 动态改变UIButton的大小

时间:2014-11-29 18:53:16

标签: ios swift

我试图动态更改UIButton的框架,但它不起作用。

@IBOutlet weak var button1: UIButton!

@IBAction func btn_move2_touchupinside(sender: AnyObject, forEvent event: UIEvent) {
           button1.frame = CGRectMake(0, 0, 100, 100)
}

我猜测我应该在帧后更改时重新加载按钮。 有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

自动布局阻止您更新按钮的框架。以下3种不同的方法可以使这项工作从最简单到最难设置:

  1. 关闭自动布局。在Interface Builder中,单击View Controller。然后在最右侧的文件检查器中,取消选中使用自动布局

  2. ViewDidLoad

    中以编程方式定义按钮
    let button = UIButton.buttonWithType(.System) as UIButton
    button.frame = CGRectMake(200, 200, 100, 100)
    button.addTarget(self, action: "btn_move2_touchupinside:forEvent:", forControlEvents: .TouchUpInside)
    button.setTitle("New Button", forState: .Normal)
    self.view.addSubview(button)
    
  3. 为您的按钮设置4个约束(从超视图前导边距开始的水平偏移,从顶部布局向导垂直偏移,宽度和高度)。为这些约束设置@IBOutlets,然后在代码中更新其constant属性。

答案 1 :(得分:-1)

只需使用此代码即可正常工作:

button.layer.frame = newFrame

或者您需要重置按钮的中心:

button.frame = newFrame
button.center = newCenter