首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CGRect未被应用

CGRect未被应用
EN

Stack Overflow用户
提问于 2017-08-19 16:15:30
回答 2查看 514关注 0票数 0

我的代码正在运行,但问题是tab映像没有被重新定位到代码中设置它的位置。它呆在viewController的位置上,没有变大,也没有移动。我在试着让它变大。

代码语言:javascript
复制
@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)

    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-19 21:49:52

如果两个UIDevice.current.model条件都是假的,因此代码永远不会执行,这是因为将返回"iPhone“、"iPod触摸”或"iPad“,而不是硬件模型。正确的做法是:

代码语言:javascript
复制
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)   
    }
}

但这段代码只能在iPhone 4s或GSM iPhone 5上运行,而不会在其他设备上运行,如CDMA iPhone 5或iPhone 6或包括iPads在内的任何其他型号。

相反,更稳健的方法将是检查屏幕大小,iPhone 4s和较低型号的屏幕大小为320x480点,iPhone 5的屏幕大小为320x568点,其他设备的屏幕大小更大。

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

代码语言:javascript
复制
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)
    }
}

但是请记住,这是一个非常糟糕的实践,您应该使用自动布局

票数 0
EN

Stack Overflow用户

发布于 2017-08-20 01:36:37

尝试以下几点:

代码语言:javascript
复制
extension UIDevice {
    var modelName: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        return identifier
    }
}

然后在这样的代码调用中:

代码语言:javascript
复制
if UIDevice.current.modelName == "iPhone4,1" {
    tab.frame = CGRect(x: 130, y: 122, width: 60, height: 60)
} else if UIDevice.current.modelName == "iPhone5,1"  {
    tab.frame = CGRect(x: 130, y: 171, width: 75, height: 75)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45773714

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档