根据设备的大小更改 UIImageViews 的位置

Changing the position of UIImageViews based on the size of the device

我有一个 UIImageView 的网格。布局在 5S 上看起来不错,但在 6 或 6+ 上,网格位于左上角。我决定尝试测试屏幕尺寸,这在 this question (The test works); then based on the screen size, re-position the UIImageViews using CGRectMake as suggested in this post 中有解释。这是代码:

if UIDevice().userInterfaceIdiom == .Phone {
                switch UIScreen.mainScreen().nativeBounds.height {
                case 480:
                    println("iPhone Classic")
                case 960:
                    println("iPhone 4 or 4S")
                case 1136:
                    println("Default Setup")
                    println("iPhone 5 or 5S or 5C")
                case 1334:
                    dieImage0.frame = CGRectMake(42, 61, 152, 152)
                    dieImage1.frame = CGRectMake(247, 61, 152, 152)
                    dieImage2.frame = CGRectMake(42, 218, 152, 152)
                    dieImage3.frame = CGRectMake(247, 218, 152, 152)
                    dieImage4.frame = CGRectMake(42, 376, 152, 152)
                    dieImage5.frame = CGRectMake(247, 376, 152, 152)
                    dieImage6.frame = CGRectMake(42, 533, 152, 152)
                    dieImage7.frame = CGRectMake(247, 533, 152, 152)
                    println("iPhone 6")
                case 2208:
                    dieImage0.frame = CGRectMake(141, 201, 228, 228)
                    dieImage1.frame = CGRectMake(819, 201, 228, 228)
                    dieImage2.frame = CGRectMake(141, 723, 228, 228)
                    dieImage3.frame = CGRectMake(819, 723, 228, 228)
                    dieImage4.frame = CGRectMake(141, 1242, 228, 228)
                    dieImage5.frame = CGRectMake(819, 1242, 228, 228)
                    dieImage6.frame = CGRectMake(141, 1764, 228, 228)
                    dieImage7.frame = CGRectMake(819, 1764, 228, 228)
                    println("iPhone 6+")
                default:
                    println("unknown")
                }
            }

我知道测试有效,因为 phone 模型的消息打印正确,但图像的位置没有改变。然后当我触发 segue 转到第二个视图控制器时

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showMenu" {
            println("You pressed the menu button")
        }

错误 "fatal error: unexpectedly found nil while unwrapping an Optional value" 被打印到控制台,案例中第一行更改我正在测试的设备的图像位置抛出此错误:Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)。知道为什么会这样吗?

试试这个,

1) 检查 imageview 的插座连接

2) 在 vi​​ewWillAppear 下添加这个函数,如下所示

override func viewWillAppear(animated: Bool) {

...
...
let screenSize: CGRect = UIScreen.mainScreen().bounds
    screenSize.origin
    let screenWidth = screenSize.width;
    let screenHeight = screenSize.height;
  if(screenHeight == 667)
  { 
   //do Something
  }
  else if(screenHeight == 667)
  {
   //do Something
  }


}