我使用的是 Swift iOS 8.0。我有以下 UIViewController 的 UI 设置,它是我使用 Xcode 6.1.1 中的界面生成器创建的。
- 主界面 View (MainView)
- 在这个主 UIView 中,我有四个子 UIView,它们水平地向下排列在屏幕上
- 在这些 UIView 中的每一个中,我都有其他类型的 View (UIImageView、UILabel 等)
现在让我们来看看最上面的子 UIView(我将其称为 SubView1)。它里面有一个 UIImageView。我想以编程方式做两件事(我不想使用 AutoLayout):
- 根据MainView的大小改变SubView1的大小
- 根据 SubView1 的新尺寸更改 UIImageView。
目前我有以下代码正在尝试执行此操作(尚未重构):
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
var mainViewWidth = self.view.bounds.width
var mainViewHeight = self.view.bounds.height
// calculate new size for subView
var subViewHeight : CGFloat = mainViewHeight / 4
var subViewWidth : CGFloat = mainViewWidth
var nextXPosn : CGFloat = 0
var nextYPosn : CGFloat = 0
// change frame size for SubView1
self.subView1.frame = CGRect(x: nextXPosn, y: nextYPosn, width: subViewWidth, height: subViewHeight)
var originalSubViewHeight : CGFloat = originalMainViewHeight / 4.0
var scaleFactor : CGFloat = subViewHeight / originalSubViewHeight
// calculate new height and width for image
var newHeight : CGFloat = subImage.bounds.height * scaleFactor
var newWidth : CGFloat = subImage.bounds.width * scaleFactor
// change frame size and position for image
self.subImage.frame = CGRect(x: 10, y: 10, width: newWidth, height: newHeight)
}
请注意,我对 x 和 y 位置使用了任意值。当此代码执行时,subImage 或 subView1 的大小或位置都不会发生变化。有什么我没有设置允许这些 View 改变位置和大小的东西吗?为什么什么都没有改变?
注意:我刚刚尝试删除更改 subView1 大小的行
self.subView1.frame = CGRect(x: nextXPosn, y: nextYPosn, width: subViewWidth, height:
subview 高度)
子图像的大小和位置现在发生了变化。似乎通过移动和更改 subView1 的大小,它可以防止更改 subImage(它的 subview )的大小和位置。我不确定为什么会这样。
最佳答案
尝试
self.subView1.frame = CGRectMake(x: nextXPosn, y: nextYPosn, width: subViewWidth, height: subViewHeight)
您使用的是 CGRect,而不是 CGRectMake。
关于ios - 更新框架属性时 UIImageView 不改变大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27663994/