在Swift中使用类别并在不同的类中使用它们

时间:2021-09-01 20:02:39

I am new to swift. I am working on creating the categories in swift. I have created one category for UIColor. I need to call this in some other class. Currently I am calling this by

我是新手。我正在努力在swift中创建类别。我为UIColor创建了一个类别。我需要在其他课程中调用它。目前我称之为

messageview.backgroundColor = UIColor(hexaString: "31D433")

but it gives an error.

但它给出了一个错误。

class Colorextension: UIColor {
    convenience init(hexaString:String) {
        self.init(
            red:   CGFloat( strtoul( String(Array(hexaString.characters)[1...2]), nil, 16) ) / 255.0,
            green: CGFloat( strtoul( String(Array(hexaString.characters)[3...4]), nil, 16) ) / 255.0,
            blue:  CGFloat( strtoul( String(Array(hexaString.characters)[5...6]), nil, 16) ) / 255.0, alpha: 1 )
    }
}

1 个解决方案

#1


2  

In swift you use extensions, placed in global scope:

在swift中,您使用扩展,放置在全局范围内:

extension UIColor {
    convenience init?(hexaString:String) {
        if hexaString.characters.count < 6 {return nil}
        self.init(
            red:   CGFloat( strtoul( String(Array(hexaString.characters)[0...1]), nil, 16) ) / 255.0,
            green: CGFloat( strtoul( String(Array(hexaString.characters)[2...3]), nil, 16) ) / 255.0,
            blue:  CGFloat( strtoul( String(Array(hexaString.characters)[4...5]), nil, 16) ) / 255.0, alpha: 1 )
    }
}

Now messageview.backgroundColor = UIColor(hexaString: "31D433") should work.

现在messageview.backgroundColor = UIColor(hexaString:“31D433”)应该可以工作。

Update

更新

Note you used wrong ranges (I corrected them), and you probably need to write failable initializer for case when input string have wrong format.

请注意,您使用了错误的范围(我更正了它们),并且您可能需要为输入字符串格式错误的情况编写可用的初始化程序。

#1


2  

In swift you use extensions, placed in global scope:

在swift中,您使用扩展,放置在全局范围内:

extension UIColor {
    convenience init?(hexaString:String) {
        if hexaString.characters.count < 6 {return nil}
        self.init(
            red:   CGFloat( strtoul( String(Array(hexaString.characters)[0...1]), nil, 16) ) / 255.0,
            green: CGFloat( strtoul( String(Array(hexaString.characters)[2...3]), nil, 16) ) / 255.0,
            blue:  CGFloat( strtoul( String(Array(hexaString.characters)[4...5]), nil, 16) ) / 255.0, alpha: 1 )
    }
}

Now messageview.backgroundColor = UIColor(hexaString: "31D433") should work.

现在messageview.backgroundColor = UIColor(hexaString:“31D433”)应该可以工作。

Update

更新

Note you used wrong ranges (I corrected them), and you probably need to write failable initializer for case when input string have wrong format.

请注意,您使用了错误的范围(我更正了它们),并且您可能需要为输入字符串格式错误的情况编写可用的初始化程序。