Swift - 动态改变UIButton的大小 [英] Swift - dynamically change size of UIButton

查看:1779
本文介绍了Swift - 动态改变UIButton的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to dynamically change frame of UIButton, but it doesn't work.

@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?

推荐答案

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

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:


  1. 关闭自动布局。在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 ,然后在代码中更新它们的常量属性。

  • Set up 4 constraints for your button (horizontal offset from superview leading margin, vertical offset from top layout guide, width, and height). Set up @IBOutlets for these constraints and then update their constant properties in code.

    这篇关于Swift - 动态改变UIButton的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆