在 Swift 中舍入一个 CGFloat [英] Round up a CGFloat in Swift

查看:48
本文介绍了在 Swift 中舍入一个 CGFloat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Swift 中对 CGFloat 进行四舍五入?我试过 ceil(CDouble(myCGFloat)) 但这只适用于 iPad Air &iPhone 5S.

How can I round up a CGFloat in Swift? I've tried ceil(CDouble(myCGFloat)) but that only works on iPad Air & iPhone 5S.

在另一个模拟设备上运行时,我收到一个错误消息,指出 'NSNumber' 不是 'CGFloat' 的子类型

When running on another simulated device I get an error saying 'NSNumber' is not a subtype of 'CGFloat'

推荐答案

更新:Apple 现在已经定义了一些 CGFloat 特定版本的常用函数,例如 ceil:

Update: Apple have now defined some CGFloat-specific versions of common functions like ceil:

func ceil(x: CGFloat) -> CGFloat

...专门用于处理 32/64 位差异.如果您只是将 ceil 与 CGFloat 参数一起使用,它现在应该适用于所有架构.

...specifically to cope with the 32/64-bit difference. If you simply use ceil with a CGFloat argument it should now work on all architectures.

我原来的回答:

我认为这很可怕,但谁能想到更好的方法?#if 似乎不适用于 CGFLOAT_IS_DOUBLE;我认为您仅限于构建配置,来自 我可以在条件编译的文档中看到.

This is pretty horrible, I think, but can anyone think of a better way? #if doesn't seem to work for CGFLOAT_IS_DOUBLE; I think you're limited to build configurations, from what I can see in the documentation for conditional compilation.

var x = CGFloat(0.5)

#if arch(x86_64) || arch(arm64)
var test = ceil(x)
#else
var test = ceilf(x)
#endif

这篇关于在 Swift 中舍入一个 CGFloat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆