colorWithAlphaComponent example in Swift

守給你的承諾、 提交于 2019-12-03 01:02:28
Mick MacCallum

It's not strange, it's behaving exactly as it should. Although many of UIColor's methods are class methods, there are still a few instance methods, and this is one of them. From the UIColor documentation.

colorWithAlphaComponent:

Creates and returns a color object that has the same color space and component values as the receiver, but has the specified alpha component.

So, colorWithAlphaComponent: just changes the alpha value of its receiver. Example:

let purple = UIColor.purpleColor() // 1.0 alpha
let semi = purple.colorWithAlphaComponent(0.5) // 0.5 alpha

And the reason why you're seeing autocompletion for this instance method on the type, is because Swift allows you to use instance methods as curried type methods. In the example you provided, colorWithAlphaComponent actually returns a function that takes a CGFloat as input and returns a UIColor.

let purple = UIColor.purpleColor()
let purpleFunc: (CGFloat -> UIColor) = UIColor.colorWithAlphaComponent(purple)

So, if you wanted to, you could call the type method passing in the instance you want to modify, and then call the resulting function with the alpha that you want to apply, like so.

let purple = UIColor.purpleColor()
let purpleTrans = UIColor.colorWithAlphaComponent(purple)(0.5)

Then as far as the issues you're having with the modal view controller go, you shouldn't be attempting to change the alpha of the view of a modal view controller. See this for more info. Instead, you should be manually creating a view and adding it to the view hierarchy of your existing view controller (if you absolutely have to alter its alpha)

Swift 4.0

self.view.backgroundColor = UIColor.black.withAlphaComponent(0.7)

in Swift 3.0

This works for me in xcode 8.2.

yourView.backgroundColor = UIColor.black.withAlphaComponent(0.5)

It may helps you.

Try smth like this to set color

 view.backgroundColor = UIColor(red: (64/255.0), green: (54/255.0), blue: (105/255.0), alpha: 1.0)

Since UIColor is part of UIKit, it has been replaced in SwiftUI with Color. The equivalent method is .opacity(_ opacity: Double) for example:

Color.purple.opacticy(0.5)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!