我有一个带有图像的按钮,我正在使用 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
}
}
按钮之前的
屏幕宽度和屏幕高度已在 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)
}
}
答案 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
执行操作,则需要禁用自动布局