无法将功能转换为方形颜色

时间:2015-12-19 23:46:43

标签: ios swift user-interface uikit

我认为我已经掌握了编程语言Swift的基础知识,所以现在我一直试图进一步研究它。今天早些时候,我读了一个关于如何生成随机颜色的问题,所以我尝试使用该函数在我的空白方块(UIView)中着色。

import UIKit

func generateColors() -> (main: UIColor, diff: UIColor) {

    let redMain: CGFloat = CGFloat(arc4random_uniform(104))
    let greenMain: CGFloat = redMain + 105.0
    let blueMain: CGFloat = redMain + 83.0

    let redColorMain: CGFloat = redMain / 255.0
    let greenColorMain: CGFloat = greenMain / 255.0
    let blueColorMain: CGFloat = blueMain / 255.0
    let main = UIColor(red: redColorMain, green: greenColorMain, blue: blueColorMain, alpha: 0.8)

    let redDiff: CGFloat = CGFloat(arc4random_uniform(104))
    let greenDiff: CGFloat = redDiff + 105.0
    let blueDiff: CGFloat = redDiff + 83.0

    let redColorDiff: CGFloat = redDiff / 255.0
    let greenColorDiff: CGFloat = greenDiff / 255.0
    let blueColorDiff: CGFloat = blueDiff / 255.0
    let diff = UIColor(red: redColorDiff, green: greenColorDiff, blue: blueColorDiff, alpha: 0.8)

    return (main, diff)
}

var square: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
square.backgroundColor = generateColors()

我尝试了很多东西,我觉得它似乎是最后功能中的参数。我是否必须调用main或diff特定的方式,对于尝试过的明显。

1 个答案:

答案 0 :(得分:1)

我不知道Swift但是a cursory look at UIView docs表明backgroundColor只是一种颜色,而不是一对颜色,除非有一些我不知道的语言。所以,而不是一对尝试:

return main;

或者:

return diff;

并将函数返回类型更改为单一颜色,无论其语法是什么(我假设为func generateColors() -> UIColor {)。

希望有帮助...