Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/95.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift中的MIN()和MAX(),并将Int转换为CGFloat_Ios_Objective C_Swift - Fatal编程技术网

Ios Swift中的MIN()和MAX(),并将Int转换为CGFloat

Ios Swift中的MIN()和MAX(),并将Int转换为CGFloat,ios,objective-c,swift,Ios,Objective C,Swift,我在以下方法中遇到一些错误: 1) 对于第一种方法,我如何将屏幕高度/cellCount作为CGFLoat返回 2) 在第二个方法中,如何使用ObjC的MIN()和MAX()的等价物 func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat { var cellCount = Int(self.tableView.numberOfRowsIn

我在以下方法中遇到一些错误:

1) 对于第一种方法,我如何
将屏幕高度/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
}
您可以只使用min()和max()-它们是内置的

如果你想推出你自己的(为什么?-也许是为了扩展它),你会使用

func myMin <T : Comparable> (a: T, b: T) -> T {
    if a > b {
        return b
    }
    return a
}
func-myMin(a:T,b:T)->T{
如果a>b{
返回b
}
归还
}

您需要将
cellCount
显式转换为
CGFloat
,因为Swift不会在整数和浮点之间进行自动类型转换:

return screenHeight / CGFloat(cellCount)

min
max
函数由标准库定义。

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

return CGFloat(screenHeight) / CGFloat(cellCount)
2:使用标准库定义的最小和最大函数。它们的定义如下:

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

如果您使用的是Swift 3,则现在对序列(即集合)调用
max()
min()
,而不是传入参数:


让高度=[5,6]
设max=heights.max()/->6
设min=heights.min()/->5

谢谢,我接受了您的回答,因为它简单明了,而且提供了完整的
min()
max()
函数。如果我刚刚将
MIN()
MAX()
转换为小写,我几乎完全正确。虽然下面有注释,但您可以用小写形式编写MIN或MAX。斯威夫特就这些。
let lower = min(17, 42) // 17
let upper = max(17, 42) // 42