简体   繁体   中英

Swift error: Can't assign value of type UIColor to type CGColor

I have two input fields in my view, loginEmailInput and loginPasswordInput .

I'm trying to change the border color. My code in ViewController.swift looks like so:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var loginPasswordInput: UITextField!
    @IBOutlet weak var loginEmailInput: UITextField!

    let borderColor : UIColor = UIColor(red:0.39, green:0.76, blue:0.37, alpha:1)
    loginEmailInput.layer.borderColor = borderColor
    loginPasswordInput.layer.borderColor = borderColor

    override func viewDidLoad() {
        super.viewDidLoad()

        //etc....

However, both these lines show an error:

loginEmailInput.layer.borderColor = borderColor
loginPasswordInput.layer.borderColor = borderColor

The error is:

Can't assign value of type UIColor to type CGColor

How do I solve this issue?

For a CALayer, use, as an example:

UIColor.blue.cgColor

In general, layers/ CALayers use CG (Core Graphics) colors. While for something like background of the view, you can use something like view.backgroundColor = .blue . UIColor is part of UIKit FrameWork (NSObject), CG is part of Core Graphic (CF/ Core Foundation Library)

Note: for very old versions of Swift (Swift 1 and 2), you would have use:

UIColor.blueColor().CGColor
imageView.layer.borderColor = UIColor.black.cgColor

We can define the color by converting UIcolor to ciColor. With the code below:

imageView.layer.borderColor = UIColor(ciColor: .blue)

in my Case: using Custom Color:

   view.layer.borderColor = Colors.Mountain.color.cgColor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM