Code Monkey home page Code Monkey logo

uicolor-hex-swift's Introduction

UIColor+Hex, now Swift.

Build Status codecov.io Carthage compatible

Convenience method for creating autoreleased color using RGBA hex string.

    // Solid color
    let strokeColor = UIColor("#FFCC00").cgColor

    // Color with alpha
    let fillColor = UIColor("#FFCC00DD").cgColor

    // Supports shorthand 3 character representation
    let backgroundColor = UIColor("#FFF")

    // Supports shorthand 4 character representation (with alpha)
    let menuTextColor = UIColor("#013E")

    // "#FF0000FF"
    let hexString = UIColor.red.hexString()

    // Convert shorthand 4 character representation (with alpha) from argb to rgba
    if let rgba = "#AFFF".argb2rgba {
        let androidBackgroundColor = UIColor(rgba)
    }

    // Convert 8 character representation (with alpha) from argb to rgba
    if let rgba = "#AAFFFFFF".argb2rgba {
        let androidFrontColor = UIColor(rgba)
    }

Release Notes

  • Upgrade to Swift 5.
  • macOS gets supported.

Installation

To add a package dependency to your Xcode project, select File > Swift Packages > Add Package Dependency and enter https://github.com/yeahdongcn/UIColor-Hex-Swift to the text field.

Simply add the following lines to your Podfile:

# required by CocoaPods 0.36.0.rc.1 for Swift Pods
use_frameworks!

pod 'UIColor_Hex_Swift', '~> 5.1.9'

Then import it where you use it:

import UIColor_Hex_Swift

(CocoaPods v0.36 or later required. See this blog post for details.)

Simply add the following line to your Cartfile:

github "yeahdongcn/UIColor-Hex-Swift" >= 5.1.9

Then add the HexColor.framework to your frameworks list in the Xcode project.

Then import it where you use it:

import HEXColor

See more in RSBarcodes_Swift and objc version

uicolor-hex-swift's People

Contributors

antoninbiret avatar bogidon avatar bradmccormack avatar eunryu avatar evenbrenna avatar jackyoustra avatar jefflopes avatar jjaychen1e avatar kchatzigeorgiou avatar kevinvance avatar kiliankoe avatar lifeisfoo avatar lukeredpath avatar lupugabriel avatar mjgaylord avatar nickskull avatar ppeelen avatar readmecritic avatar seanphoenix avatar timpickles avatar uny avatar yanmeow avatar yeahdongcn avatar yichizhang avatar zhouhao27 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uicolor-hex-swift's Issues

This bundle is invalid

TMS-90049: This bundle is invalid - The bundle at path Payload/***.app/Frameworks/UIColor_Hex_Swift.framework has an invalid CFBundleIdentifier 'UIColor_Hex_Swift' There are invalid characters(characters that are not dots, hyphen and alphanumerics) that have been replaced with their code point 'UIColor\u005fHex\u005fSwift' CFBundleIdentifier must be present, must contain only alphanumerics, dots, hyphens and must not end with a dot. [see the Core Foundation Keys at

'UIColor_Hex_Swift', '~> 5.1.6'

Can't find package with Xcode 13.1

Hi,

Thanks for offering a great package.

Swift Package Manager can no longer find UIColor-Hex-Swift after updating to the latest version of Xcode.

Any idea why?

Thanks!
Blessings,
--Mark

Carthage build fails for WatchOS

I'm using Carthage to get UIColor-Hex and since the latest Xcode update the repo fails to compile for all architectures.

When I run carthage update I get this error when it reaches the HexColor:

*** Checking out UIColor-Hex-Swift at "2.0"
*** xcodebuild output can be found in /var/folders/06/dgpth9f15tsb1r1_j34528x40000gn/T/carthage-xcodebuild.G2t9PI.log
*** Building scheme "HEXColor-watchOS" in HEXColor.xcodeproj
** CLEAN FAILED **


The following build commands failed:
    Check dependencies
(1 failure)
** BUILD FAILED **


The following build commands failed:
    Check dependencies
(1 failure)
A shell task failed with exit code 65:
** CLEAN FAILED **


The following build commands failed:
    Check dependencies
(1 failure)
** BUILD FAILED **


The following build commands failed:
    Check dependencies
(1 failure)

version 4.0.0 it's not yet on cocoapods

Hi,
When I try pod 'UIColor_Hex_Swift', '~> 4.0.0' it cause error on pod update. It seems version 4 it's not updated on cocoapods yet.
I used pod 'UIColor_Hex_Swift', :git => 'https://github.com/yeahdongcn/UIColor-Hex-Swift.git' and it works

Undefined symbols for architecture x86_64

Tried to build the app on Swift 3.0, XCode version 8.2.1
I got the error on linking step.

Undefined symbols for architecture x86_64:
"(extension in UIColor_Hex_Swift):__ObjC.UIColor.(init (Swift.String, defaultColor : __ObjC.UIColor) -> __ObjC.UIColor).(default argument 1)"

XCode 11 showing expression is ambiguous without more context

i have this little piece in my code

UIView.animate(withDuration: 0.1, animations: { _ in
      self.highlightedCell!.backgroundColor = UIColor.init(hex6: 0xF7DB69)
})

and it complains with Type of expression is ambiguous without more context
i cant figure it out.. any clue?

UIColor convert to hex problem!!

public func hexString(_ includeAlpha: Bool) -> String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        
        if (includeAlpha) {
            return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255))
        } else {
            return String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
        }
    }

return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255))

this line should be

return String(format: "#%02X%02X%02X%02X", Int(round(r * 255)), Int(round(g * 255)), Int(round(b * 255)), Int(round(a * 255)))

if don't round, after convert to hex, hex to UIColor could loss of precision

example rgb 27 34 48, after it will be 27 33 47

Minimum deployment target using Carthage

Using Carthage to install UIColor-Hex-Swift and my project's deployment target set to iOS 8.0, I get this error when building:

"Module file's minimum deployment target is ios9.0 v9.0"

Looking at the pod spec, it seems that the minimum version should be 8.0.

Argument Labels Don't Match Overloads Issue

Hey,

Great git guys.

I followed the installation process and I get an error:
Argument labels '(rgba:)' do not match any available overloads')' when i try to add this line in my App Delegate

    UITabBar.appearance().barTintColor = UIColor(rgba: "#12296f")

Do i have to add an import statement? If so what is it? What am i missing?

Thanks a lot

'substring(from:)' is deprecated in Swift 4

Hi, in Swift 4, your library says 'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator. in too many places. Can you fix it?

Invalid hex strings produced from wide display colors

The documentation for getRed(: green: blue: ) explains that older versions of iOS always set the values to a range within 0 and 1, but not any more. When one of these returns outside the expected range, hexString(:) produces invalid hex codes (for example, #54A8FFFFFFDF).

Swift Package Manager

I see that the support for SPM has been added, when you will release a new version in order to be able to add the package to SPM?

Now I have the following error:
Screenshot 2019-10-05 at 17 14 47

set proper name of pod

to not get mistakes
pod 'UIColor-Hex-Swift'
or
pod 'UIColor_Hex_Swift'

Or specify it in radme

Could not find member 'CGColor'

I install this library via cocoapod but I got this error message

Could not find member 'CGColor'

Please advice. Thank you.

Support MacOS

Can you add support for MacOS
You can do it easily with an typealias

I've had to import it to my Mac Project from source rather than cocoapods. Would prefer Cocoapods.

A quick way to support
macos
Just replace top of
UIColorExtension.swift

import UIKit
@objc extension UIColor {

WITH


#if os(iOS)
//---------------------------
//iOS
//---------------------------
import Foundation
import UIKit
typealias AppColor = UIColor

//---------------------------
#elseif os(macOS)
//---------------------------
//macOS
//---------------------------
import Cocoa
typealias AppColor = NSColor

//---------------------------
//#else
// os(tvOS) || os(watchOS)
//---------------------------
#endif


@objc extension AppColor {
    /**
     The shorthand three-digit hexadecimal representation of color.
     #RGB defines to the color #RRGGBB.
     
     - parameter hex3: Three-digit hexadecimal value.
     - parameter alpha: 0.0 - 1.0. The default is 1.0.
     */
    public convenience init(hex3: UInt16, alpha: CGFloat = 1) {
        let divisor = CGFloat(15)
        let red     = CGFloat((hex3 & 0xF00) >> 8) / divisor
        let green   = CGFloat((hex3 & 0x0F0) >> 4) / divisor
        let blue    = CGFloat( hex3 & 0x00F      ) / divisor
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
...}

Swift 5 was throwing errors about failable inits and non failable in
I had to change
init

   public convenience init(_ rgba: String, defaultColor: NSColor = NSColor.clear) {

TO init?

public convenience init?(_ rgba: String, defaultColor: NSColor = NSColor.clear) {

Failable init?

Any considerations to make the init method failable? Or provide an optional failable init?

It makes much more sense to me the init to be failable in case of an invalid string, as it allows for much better error handling than printing a message in the console.

Support Application Extensions

When including this library in an application extension, I get the following warning:
Linking against a dylib which is not safe for use in application extensions. All that should be required to supress this warning is to set the target’s “Require Only App-Extension-Safe API” build setting to Yes.

Dependency "UIColor-Hex-Swift" has no shared framework schemes

I'm using Carthage 0.9.3 and get this error when trying to use UIColor-Hex-Swift:

*** Checking out UIColor-Hex-Swift at "1.2"
*** Skipped building UIColor-Hex-Swift due to the error:
Dependency "UIColor-Hex-Swift" has no shared framework schemes

Use methods in objective c class in swift 4 project

Hi,
I have an objective-c class in swift 4 based project, I wanted to use this method, After successfully importing you pod in my objC class, methods had not been recognized.
I unlocked the UIColorExtension.swift and added @objc tag to your extension so i could use its method in my class

would you add this tag to your class for compatible it by objetive c classes ?

thanks

in case you want to extend to support rgb(r,g,b) and rgba(r,g,b,a) strings

not sure how efficient these are yet since they use advance o(n) parsing for likely utf8 single byte strings

you'd call this method in the else not hex clause

func rgbaStringToVals(rgba: String) -> (r: CGFloat,g: CGFloat,b: CGFloat,a: CGFloat) {
var red = CGFloat(0.0)
var green = CGFloat(0.0)
var blue = CGFloat(0.0)
var alpha = CGFloat(1.0)

if rgba.hasPrefix("rgba(") {
    let sInd = advance(rgba.startIndex,5)
    let eInd = advance(rgba.startIndex,count(rgba)-1)
    var num = rgba[sInd..<eInd]
    var loc = num.componentsSeparatedByString(",")
    if count(loc) < 4 {
        println("unable to find 4 color values from string \(rgba) default color used rgba(0,0,0,1)")
    }
    else {
        red = CGFloat(loc[0].toInt()!)/CGFloat(255.0)
        green = CGFloat(loc[1].toInt()!)/CGFloat(255.0)
        blue = CGFloat(loc[2].toInt()!)/CGFloat(255.0)
        alpha = CGFloat(loc[3].toInt()!)/CGFloat(255.0)
    }
}
else if rgba.hasPrefix("rgb(") {
    let sInd = advance(rgba.startIndex,4)
    let eInd = advance(rgba.startIndex,count(rgba)-1)
    var num = rgba[sInd..<eInd]
    var loc = num.componentsSeparatedByString(",")
    if count(loc) < 3 {
        println("unable to find 3 color values from string \(rgba) default color used rgba(0,0,0,1)")
    }
    else {
        red = CGFloat(loc[0].toInt()!)/CGFloat(255.0)
        green = CGFloat(loc[1].toInt()!)/CGFloat(255.0)
        blue = CGFloat(loc[2].toInt()!)/CGFloat(255.0)
    }

}
else {
    println("String \(rgba)does not have #hex or rgb() or rgba() format default color used rgba(0,0,0,1)")
}
return (red,green,blue,alpha)

}

Updated count() for Xcode 7 beta 5

I had to update count(hex) to hex.characters.count to make this work with Xcode 7 beta 5
I forked your repository, but thought you should know.

Prefix

Why this:

        guard rgba.hasPrefix("#") else {
            throw UIColorInputError.missingHashMarkAsPrefix
        }
        
        let hexString: String = String(rgba[String.Index.init(encodedOffset: 1)...])
//...

Not:

        var hexString = rgba
        if hexString.hasPrefix("#") {
            hexString = String(hexString.dropFirst())
        }
//...

The different name between SwiftPackageManager and Cocoapod

When I create third part SDK depend on UIColor-Hex-Swift , because of the different name between SwiftPackageManager and Cocoapod, I cant import in the SDK to my app.

when I use the SwiftPackageManage name in my SDK, I cant pod trunk push my SDK to remote, but when I use Pod name in my SDK, I cant use SwiftPackageManage to install my SDK in my App.

Troubles with podspec

When trying to install pod I get the following error
Re-creating CocoaPods due to major version update.
Analyzing dependencies
[!] Unable to find a specification for UIColor_Hex_Swift (~> 2.1)

My cocopods version is 1.0.0

Archive export issues when used as a Swift Package

We recently started migrating from Cocoapods to SwiftPM for our projects and I faced this issue while exporting an archive:

+ xcodebuild -exportArchive -exportOptionsPlist /var/folders/3v/vf11v3tx64j79b239rzbg_280000gn/T/gym_config20211103-77126-b4sgdz.plist -archivePath '/Users/{SANITIZED_USERNAME}/Library/Developer/Xcode/Archives/2021-11-03/{SANITIZED_PROJECT_NAME} 2021-11-03 17.32.44.xcarchive' -exportPath /var/folders/3v/vf11v3tx64j79b239rzbg_280000gn/T/gym_output20211103-77126-1ub76v
2021-11-03 17:34:05.031 xcodebuild[81855:2683877] [MT] IDEDistribution: -[IDEDistributionLogging _createLoggingBundleAtPath:]: Created bundle at path "/var/folders/3v/vf11v3tx64j79b239rzbg_280000gn/T/{SANITIZED_PROJECT_NAME}_2021-11-03_17-34-05.031.xcdistributionlogs".
2021-11-03 17:34:46.374 xcodebuild[81855:2683877] -[NSNull path]: unrecognized selector sent to instance 0x1fa120340
** INTERNAL ERROR: Uncaught exception **
Uncaught Exception: -[NSNull path]: unrecognized selector sent to instance 0x1fa120340
Stack:
  0   __exceptionPreprocess (in CoreFoundation)
  1   objc_exception_throw (in libobjc.A.dylib)
  2   -[NSObject(NSObject) __retain_OA] (in CoreFoundation)
  3   ___forwarding___ (in CoreFoundation)
  4   _CF_forwarding_prep_0 (in CoreFoundation)
  5   -[IDEDistributionProcessingPipeline process:] (in IDEFoundation)
  6   -[IDEDistributionPackagingStep loadFromExportOptions:error:] (in IDEFoundation)
  7   -[IDEDistributionDriver runWithDestinationPath:error:] (in IDEFoundation)
  8   -[Xcode3CommandLineBuildTool _distributeArchiveAndExit] (in Xcode3Core)
  9   -[Xcode3CommandLineBuildTool run] (in Xcode3Core)
 10   main (in xcodebuild)
 11   start (in dyld)

/Users/{SANITIZED_PROJECT_NAME}/.rvm/gems/ruby-3.0.0/gems/fastlane-2.197.0/gym/lib/assets/wrap_xcodebuild/xcbuild-safe.sh: line 61: 81855 Abort trap: 6           xcodebuild "$@"

When I removed the UIColor-Hex-Swift from Swift Package dependencies the issue was resolved. Please note that using it with Cocoapods does not reproduce the above issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.