ios - Swift 中的 MIN() 和 MAX() 并将 Int 转换为 CGFloat

标签 ios objective-c swift

我在使用以下方法时遇到了一些错误:

1) 对于第一种方法,我如何将 screenHeight/cellCount 作为 CGFLoat 返回?

2) 如何在第二种方法中使用 ObjC 的 MIN() 和 MAX() 等效项?

func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
    var cellCount = Int(self.tableView.numberOfRowsInSection(indexPath.section))

    return screenHeight / cellCount as CGFloat
}

// #pragma mark - UIScrollViewDelegate

func scrollViewDidScroll(scrollView: UIScrollView) {
    let height = CGFloat(scrollView.bounds.size.height)
    let position = CGFloat(MAX(scrollView.contentOffset.y, 0.0))

    let percent = CGFloat(MIN(position / height, 1.0))
    blurredImageView.alpha = percent
}

最佳答案

1:您不能从 Int 向下转换为 CGFloat。您必须使用 Int 作为输入来初始化 CGFloat。

return CGFloat(screenHeight) / CGFloat(cellCount)

2:使用标准库定义的 min 和 max 函数。它们的定义如下:

func min<T : Comparable>(x: T, y: T, rest: T...) -> T
func max<T : Comparable>(x: T, y: T, rest: T...) -> T

用法如下。

let lower = min(17, 42) // 17
let upper = max(17, 42) // 42

关于ios - Swift 中的 MIN() 和 MAX() 并将 Int 转换为 CGFloat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24201769/

相关文章:

ios - 如何在用户首次登录后自动登录?

ios - 使用自定义字体而不包含在info.plist ios中

ios - 为什么我的CAReplicatorLayer旋转时会有偏移

ios - 想要了解如何直接从我的 iOS 应用程序发送电子邮件?山魈或邮件枪选项

objective-c - MBProgressHUD 不会显示

iphone - 创建协议(protocol)后访问 UIPageViewController 的委托(delegate)方法

ios - 矩形交叉点的数量?

iphone - 添加单元格后,iOS UITableView 不滚动

ios - SSZipArchive 从 Url 解压

swift - 当明显有数据时,Firebase 字典返回 nil