[英]Swift - dynamically change size of UIButton
我正在尝试动态更改UIButton的框架,但它不起作用。
@IBOutlet weak var button1: UIButton!
@IBAction func btn_move2_touchupinside(sender: AnyObject, forEvent event: UIEvent) {
button1.frame = CGRectMake(0, 0, 100, 100)
}
我猜我应该在帧改变后重新加载按钮。 有人可以帮忙吗?
自动布局阻止您更新按钮的框架。 以下3种不同的方法可以使这项工作从最简单到最难设置:
关闭自动布局。 在Interface Builder中,单击View Controller。 然后在最右侧的文件检查器中 ,取消选中“ 使用自动布局” 。
在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)
为您的按钮设置4个约束(从超视图前缘开始的水平偏移,从顶部布局向导的垂直偏移,宽度和高度)。 为这些约束设置@IBOutlets
,然后在代码中更新它们的constant
属性。
只需使用此代码即可正常工作:
button.layer.frame = newFrame
或者您需要重置按钮的中心:
button.frame = newFrame
button.center = newCenter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.