无法使用CGRectMake调整UIButton的大小

时间:2016-08-31 08:54:13

标签: ios swift uianimation cgrectmake

我有一个带有图像的按钮,我正在使用 UIView.animateWithDuration 为视图和图像视图指定新的尺寸。

视图正确缩放,但图像视图没有变化

代码段:

@IBAction func imageButtonDidTouch(sender: AnyObject) {

    UIView.animateWithDuration(0.7) { 

        /*** Executes Properly ***/
        self.dialogView.frame = CGRectMake(0, 0, self.screenWidth!, self.screenHeight!)

        /*** Does Not Execute ****/
        self.imageButton.frame = CGRectMake(0, 0, self.screenWidth!, 240)


        /*** Executes Properly ***/
        self.likeButton.hidden = true
        self.shareButton.hidden = true
        self.userButton.hidden = true
        self.headerView.hidden = true
        self.dialogView.layer.cornerRadius = 0

    }

}
按钮之前的

屏幕截图: enter image description here

按钮按下后的屏幕截图: enter image description here

屏幕宽度和屏幕高度已在 viewDidLoad()

中定义
screenWidth = UIScreen.mainScreen().bounds.width
   screenHeight = UIScreen.mainScreen().bounds.height

编辑1: imageButton声明

@IBOutlet weak var imageButton: UIButton!

编辑2: 我在animate函数中添加了一个完成处理程序:

    @IBAction func imageButtonDidTouch(sender: AnyObject) {


    print("Height Before:", self.imageButton.frame.height)
    print("Width Before:",self.imageButton.frame.width)

    UIView.animateWithDuration(0.7, animations: { 

                    /*** Executes Properly ***/
                    self.dialogView.frame = CGRectMake(0, 0, self.screenWidth!, self.screenHeight!)

                    /*** Does Not Execute ****/
                    self.imageButton.frame = CGRectMake(0, 0, self.screenWidth!, 240)


                    /*** Executes Properly ***/
                    self.likeButton.hidden = true
                    self.shareButton.hidden = true
                    self.userButton.hidden = true
                    self.headerView.hidden = true
                    self.dialogView.layer.cornerRadius = 0



        }) { (true) in


            print("Height After:", self.imageButton.frame.height)
            print("Width After:",self.imageButton.frame.width)

    }

}

控制台截图: enter image description here

查看层次结构: enter image description here

1 个答案:

答案 0 :(得分:1)

在设置imageButton尺寸之前检查是否接收到所需的screenWidth。

获取UIScreen帧数据的正确位置在viewDidLayoutSubviews,因为在子视图已在屏幕中布局后调用它也会在每次设备更改方向(例如您的方向)后调用当您的用户进入横向模式时,宽度会有所不同。这是在viewWillAppear:

之后调用的
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    screenWidth =  UIScreen.mainScreen().bounds.width
    screenHeight = UIScreen.mainScreen().bounds.height
  }

然后: -

如果您正在初始化并声明按钮以编程方式

print(self.screenWidth)

self.imageButton.frame.size = CGSizeMake(self.screenWidth,240)

如果您使用 AutoLayout 作为约束,则: -

  • 在班级

    中创建按钮宽度约束的@IBOutlet
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    
  • 然后相应地设置。

     widthConstraint = self.screenWidth
    
  

注意:   对于不使用自动布局的条件,当视图嵌入视图中时, CGRectMake 功能仅对父视图执行,而不对子视图执行。

如果需要使用CGRectMake执行操作,则需要禁用自动布局