[英]Swift - dynamically change size of UIButton
I'm trying to dynamically change frame of UIButton, but it doesn't work. 我正在尝试动态更改UIButton的框架,但它不起作用。
@IBOutlet weak var button1: UIButton!
@IBAction func btn_move2_touchupinside(sender: AnyObject, forEvent event: UIEvent) {
button1.frame = CGRectMake(0, 0, 100, 100)
}
I'm guessing that I should reload button after frame is changed. 我猜我应该在帧改变后重新加载按钮。 Can anybody help?
有人可以帮忙吗?
Auto Layout is preventing you from updating your button's frame. 自动布局阻止您更新按钮的框架。 Here are 3 different ways you can make this work from easiest to set up to hardest:
以下3种不同的方法可以使这项工作从最简单到最难设置:
Turn off Auto Layout. 关闭自动布局。 In Interface Builder, click on your View Controller.
在Interface Builder中,单击View Controller。 Then in the File Inspector on the far right, uncheck Use Auto Layout .
然后在最右侧的文件检查器中 ,取消选中“ 使用自动布局” 。
Define your button programmatically in ViewDidLoad
: 在
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)
Set up 4 constraints for your button (horizontal offset from superview leading margin, vertical offset from top layout guide, width, and height). 为您的按钮设置4个约束(从超视图前缘开始的水平偏移,从顶部布局向导的垂直偏移,宽度和高度)。 Set up
@IBOutlets
for these constraints and then update their constant
properties in code. 为这些约束设置
@IBOutlets
,然后在代码中更新它们的constant
属性。
Just use this code will work fine: 只需使用此代码即可正常工作:
button.layer.frame = newFrame
Or you will need to reset the center of the button: 或者您需要重置按钮的中心:
button.frame = newFrame
button.center = newCenter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.