ios - CGRect 未应用

标签 ios swift frame cgrect

我的代码运行了,但问题是选项卡图像没有被重新定位到我在代码中设置的位置。它停留在 viewController 中的位置,没有变大或移动。我正在努力把它做得更大。

@IBOutlet weak var tab: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

if UIDevice.current.model == "iPhone4,1" {

        tab.frame = CGRect(x: 130, y: 122, width: 60, height: 60)

    } else if UIDevice.current.model == "iPhone5,1"  {
        tab.frame = CGRect(x: 130, y: 171, width: 75, height: 75)

    }
}

最佳答案

两个 if 条件都将为 false,因此代码永远不会执行,这是因为 UIDevice.current.model 将返回“iPhone” em>、“iPod touch”“iPad” 而不是硬件型号。正确的做法是:

override func viewDidLoad() {
    super.viewDidLoad()

    var systemInfo = utsname()
    uname(&systemInfo)

    // Retrive the device model
    let model = Mirror(reflecting: systemInfo.machine).children.reduce("") { model, element in
        guard let value = element.value as? Int8, value != 0 else { return model }
        return model + String(UnicodeScalar(UInt8(value)))
    }

    if model == "iPhone4,1" {
        tab.frame = CGRect(x: 130, y: 122, width: 60, height: 60)
    } else if model == "iPhone5,1"  {
        tab.frame = CGRect(x: 130, y: 171, width: 75, height: 75)   
    }
}

But this code will run only on an iPhone 4s or a GSM iPhone 5 and will not run on other devices like: a CDMA iPhone 5 or an iPhone 6 or any other model including iPads.

更可靠的方法是检查屏幕尺寸,iPhone 4s 及更低型号的屏幕尺寸为 320x480 点,iPhone 5 的屏幕尺寸为 320x568> 一点,其他设备的屏幕尺寸更大。

我们不会针对特定设备,而是针对特定尺寸。因此,如果屏幕高度大于 480 点,我们将在第一个 if block 内运行代码,否则我们将在第二个 block 上运行代码,如下所示:

override func viewDidLoad() {
    super.viewDidLoad()

    if UIScreen.main.bounds.size.height > 480 {
        tab.frame = CGRect(x: 130, y: 122, width: 60, height: 60)
    } else {
        tab.frame = CGRect(x: 130, y: 171, width: 75, height: 75)
    }
}

但请记住,这是一个非常糟糕的做法,您应该使用 Auto Layout相反。

关于ios - CGRect 未应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45773714/

相关文章:

ios - 有没有办法在 Xcode 7 上获取 iOS 7 模拟器

ios - 如何删除 ios 应用程序的 tmp 目录文件?

ios - 防止重复的用户名导致线程 1 : signal SIGABRT

iphone - 更改 UISearchBar 中取消按钮的框架

android - Frame OutlineColor 不适用于 Android、Xamarin Forms

ios - 一次移动多个对象 - iOS

ios - 如何为所有分辨率制作全屏图像

ios - FaSTLane 健身房失败退出状态 : 1 although Archive Succeeded

ios - 在静态函数中使用计算值

ios - 用两种不同的颜色对图像进行着色