Git Product home page Git Product logo

rastislavmirek / flexcolorpicker Goto Github PK

View Code? Open in Web Editor NEW
255.0 9.0 52.0 17.28 MB

Modern color picker library written in Swift 5 that can be easily extended and customized. It aims to provide great UX and performance with stable, quality code.

License: MIT License

Objective-C 0.30% Swift 98.78% Ruby 0.91%
color-picker picker-component swift visual hsb-color-palette rgb-controller hsb-color-model uikit-framework flexibility ui-components

flexcolorpicker's Introduction

Build Status License Badge Pod Version Badge Swift Version Badge

Flex Color Picker

Hackable color picker library written in Swift 5 that can be easily extended and customized. It aims to provide great UX and performance with stable, quality code. Includes controls for both HSB and RGB color models.

Default Flex Color Picker Preview Color Picker with All Controls Preview

Features

Default Color Picker with Rectangular Palette Preview Custom Color Picker Controls Written in Swift Preview

Use Cases

  1. plug & play color picker that works great out-of-box
  2. agile library that supports components positioning with autolayout and customisation directly from storyboard
  3. framework that allows adding your own sliders, palettes & previews or modifying existing ones without changing the code of the library
  4. combine 3 approaches above freely to get the level of customisation that you need

Instalation

Swift Package Manager

In XCode 11 and above click FileSwift PackagesAdd Package Dependency... → choose target to add FlexColorPicker to → enter https://github.com/RastislavMirek/FlexColorPicker, press next → set version prefference and confirm.

Alternativelly, if you are using Package.swift just add this dependency:

dependencies: [
    .package(url: "https://github.com/RastislavMirek/FlexColorPicker.git", from: "1.3.1")
]

Cocoapods

Add this to your podfile:

pod 'FlexColorPicker'

You can also try the Demo project with following command:

pod try FlexColorPicker

Direct Instalation

If you are not Cocoapods or SPM user you can clone the color picker from repository with this command:

git clone https://github.com/RastislavMirek/FlexColorPicker

Alternativelly, you can download latest release as ZIP from releases.

Then open the cloned/downloaded project in XCode and compile target FlexColorPicker. File FlexColorPicker.framework will be created in Products directory. Open project that you want to add the color picker to in XCode, select project file, select your application's target on the left side, select General tab and add FlexColorPicker.framework under Embedded Binaries section.

Default HSB Color Picker Preview

Basic Usage (Plug & Play)

The fastest and simplest way to add color picker to your project is using DefaultColorPickerViewController. You can add it either via storyboard or via code. In both cases you will need to implement ColorPickerDelegate protocol to receive update when a user selects color using the DefaultColorPickerViewController:

// MyController is the controller that presents DefaultColorPickerViewController
extension MyController: ColorPickerDelegate {

    func colorPicker(_ colorPicker: ColorPickerController, selectedColor: UIColor, usingControl: ColorControl) {
        // code to handle that user selected a color without confirmed it yet (may change selected color)  
    }
    
    func colorPicker(_ colorPicker: ColorPickerController, confirmedColor: UIColor, usingControl: ColorControl) { 
        // code to handle that user has confirmed selected color
    }
}

Both functions in ColorPickerDelegate are optional. You can only use one of them or both in conjuncion.

Adding via Storyboard

In storyboard, FlexColorPicker can be used by specifying Class of a view controller to be DefaultColorPickerViewController. That is done in Identity Inspector in right panel under Custom Class. Basic customisation of the controller is supported in storyboard via properties in Attributes Inspector. Delegate of DefaultColorPickerViewController can only be set in code:

class MyController {
    @IBOutlet var pickerController: ColorPickerController!
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destinationColorPicker = segue.destination as? ColorPickerControllerProtocol {
            destinationColorPicker.delegate = self
        }
    }
}

Adding via Code

DefaultColorPickerViewController can be displayed like this if using a navigation controller:

let colorPickerController = DefaultColorPickerViewController()
colorPickerController.delegate = self
navigationController?.pushViewController(colorPickerController, animated: true)

Replace the 3rd line of the above snippet with following code to display color picker modally:

let navigationController = UINavigationController(rootViewController: colorPickerController)
present(navigationController, animated: true, completion: nil)

All the above code should go to handler that triggers color picker display (e.g. handler of "Pick Color" button press).

If preffered, you can use following code to set DefaultColorPickerViewController to use rectangular, rather than radial hue-saturation pallete. See third animated image on this page for example.

colorPickerController.useRadialPalette = false

You can also set 3 additional properties that influence how color picker looks when rectangular palette is used (rectangularPaletteBorderOn, rectangularPaletteHueHorizontalInPortrait and rectangularPaletteHueHorizontalInLandscape). See in-code documentation for details. For more customisation please refer to section Customisation below.

Custom Usage

DefaultColorPickerViewController is plug & play option (see Basic Usage) with limited customisation. It is a convinince "ready-to-use" view controller which makes use of FlexColorPicker's color controls and color picker controllers. Color controls are UIViews that (usually) subclass UIControl and allow user to pick desired color and color picker controllers manage them. If more flexibility than what DefaultColorPickerViewController provides is needed, you can use them dirrectly:

  1. If custom layout of color controls is needed, read Custom Layout.
  2. If custom look or behavior of color color controls is needed, read []
  3. If both custom layout and behavior/look of color controls is needed, combine the above two approaches.

Custom Layout

Provided color controls include hue/saturation palettes (circular or rectangular), sliders for saturation, brightness and for RGB components and a picked color preview control.

Custom Controls & Behavior

Additional can by added by implementing ColorControl protocol.

Available Color Controls

Each color control has some properties (some of them can be set in storyboard) that can be used for customisation of that control's look and feel. This is the list of included color controls:

ColorPreviewWithHex RadialPaletteControl RectangularPaletteControl SaturationSliderControl BrightnessSliderControl RedSliderControl GreenSliderControl BlueSliderControl

If you want to customize your color picker, you can choose and lay out color controls that you want, set their properties if needed and connect them by adding them to the same color picker controller.

Working with Color Picker in XCode Storyboard

Connecting Color Controls

In storyboard, lay out color controls and set their classes in Identity Inspector to classes of controls you want to use. For example, set class field in in Identity Inspector to text "RadialPaletteControl". Then set controller's class to CustomColorPickerViewController, open its Connection Inspector (right side of this image) and connect corresponding outlets the controls. The same can be done in code simply by assigning color controls to appropriate properties of CustomColorPickerViewController.

If you cannot subclass CustomColorPickerViewController e.g. because your controller is a subclass of another class use ColorPickerController instead. It can also be used in storyboard as interface builder custom object. It has same properties as CustomColorPickerViewController (actually, CustomColorPickerViewController is just a convenience wrapper for ColorPickerController). You can also add color controls to it via ColorPickerController.addControl(:) so you are not limited to properties.

Once added to a color picker controller (e.g. ColorPickerController) a color control will be synchronized with other controls managed by the same controller together selecting a single color.

Extending & Overriding

FlexColorPicker is made to be tweaked and extended with minimum effort. You can add you own color control by implementing ColorControl protocol or extending one of following subclass-ready classes:

In many cases there will be no need to subclass ColorSliderControl or ColorPaletteControl. They both relay on their color delegates in how they handle color updates, present themselves and how they interpret user interactions. Therefore, you can instead implement ColorSliderDelegate or ColorPaletteDelegate protocols respectively to change look and behavior without changing the code of the control itself.

Demo project has good examples on both approaches (overriding and composition) and their combination, feel free to check it.

When subclassing AbstractColorControl or AdjustedHitBoxColorControl directly ( not via ColorSliderControl or ColorPaletteControl) you might want to override gestureRecognizerShouldBegin(:). By default, no UIPanGestureRecognizer is allowed to recognize any gesture on instances of AbstractColorControl. Depending on type of your custom color control you might want to allow UIPanGestureRecognizer to recognize the gesture in some (or all) cases. For example, horizontal slider will want to prevent UIPanGestureRecognizer from recognizing horizontal pan gesture because that means changing slider's value. In the same time, it may allow UIPanGestureRecognizer to recognize any vertical pan gesture as by those user probably ment to scoll the superview of the slider (it might be UIScrollView), not changing slider's value.

Tips & Troubleshooting

All classes and functions of FlexColorPicker have great in-code documentation. It is there to help you when you are unsure about that class or function's purposer or usage.
☛ Just option-click name of any FlexColorPicker class or function in XCode to display detailed documentation.

When setting up slider controls in storyboard it is a good practise to set its background to be transparent. Alignment rectangle (rectangle that autolayout uses to lay out the control) is smaller than the actual frame of the slider to allow for extra hit box margin as well as background framing of the slider. Therefore, if background is solid white it can overlap other views close to it.
☛ If you do not want this behavior, set Hit Box Inset to 0 in Attributes Inspector or set hitBoxInset to 0 in code.

ColorPreviewWithHex can be tapped. When it it tapped, ColorPickerController calls ColorPickerDelegate.colorPicker(_:selectedColor:usingControl:) on its delegate.
☛ You can communicate this feature to your users or opt out by setting ColorPreviewWithHex.tapToConfirm to false.

Scrolling & Modal Presentation Concerns

When you create your own color controls that do not inherit from AbstractColorControl and add use them with a modally presented UIViewController, their pan gestures may conflict with dismiss modal gesture on iOS 13. The pan gesture may also conflict with scrolling when they are subclass of UIScrollView.
☛ Solve this by adding following code to the view that receives touches (bottom most one in view hierarchy) of your custom color control:

override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    return !(gestureRecognizer is UIPanGestureRecognizer)
}

Implementation of all provided color controls (including AbstractColorControl and AdjustedHitBoxColorControl) overrides gestureRecognizerShouldBegin(:) in order to ensure that the color controls work correctly when embeded inside UIScrollViews and iOS 13 modal view conctollers presented modally. The implametation prevents instaces of UIPanGestureRecognizer from recognizing any gesture if some condition is met. In some rare cases this may interfere with custom UIPanGestureRecognizers that you add to view hierarchy.
☛ Solve this by subclassing the color control that you want to use with your UIPanGestureRecognizer and overriding gestureRecognizerShouldBegin(:) so that the gesture is recognized.

When you add a subview to a color control (either your custom color control or any of the provided ones), that subview has user interaction enabled and the color control is embedded inside a UIScrollView or iOS 13 modally presented view controller you may experience following issue when panning/swiping that subview: Panning/swiping meant to interact with your control control might be interpreted as scrolling/dismissing the controller or vice-versa.
☛ Solve this by adding following code to the subview that you added to the color control and setting the delegate to the color control itself:

weak var delegate: LimitedGestureViewDelegate?

override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    guard let delegate = delegate else {
        return !(gestureRecognizer is UIPanGestureRecognizer)
    }
    return delegate.gestureRecognizerShouldBegin(gestureRecognizer)
}

Getting in Touch

If you like it, have a question or want to hire iOS developers shoot me a message at

[my first name, see profile] at [epytysae spelled backwards] dot [first 4 letters of word information]

Emails go directly to author of FlexColorPicker, cryptic format is just spam bot protection.

Suggestions, feedback, bug reports & pull requests are very welcomed.

Thanks

Visual of slider control was inspired by popular Objective-C library HRColorPicker. Thank you for using FlexColorPicker! If you just have 3 seconds to give back, please star this repository.

flexcolorpicker's People

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

flexcolorpicker's Issues

ColorPickerDelegate

func colorPicker(_: ColorPickerController, confirmedColor: UIColor, usingControl: ColorControl) {
}

This Delegate Method will not call Please suggest me..

Brightness slider control is inverted

Hi! The brightness slider control is actually inverted (from brighter to darker). The control shows brighter as 0% and darker as 100%.

There is anyway to use this control as a default brightness control, from 0% (dark) to 100% (bright)?

Thanks in advance!

SwiftUI support needed

Logic e.g. computations to translate between HSB and RGB color models and control delegates can be reused but views needs to be added for SwiftUI.

Import with XCode 11 SwiftPackageManager doesn´t compile

Hi Rastislav,
thank you so much for updating Package.Swift
The import via XCode 11/Swift Packages/Add Package Dependency now works. :-)

But unfortunately, I get 104 Compiler Errors.

The first one is:
//
// LimitedGestureViewDelegate.swift
// FlexColorPicker
//
// Created by Rastislav Mirek on 29/9/19.
//
// MIT License
// Copyright (c) 2018 Rastislav Mirek
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

public protocol LimitedGestureViewDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool
}
Use of undeclared type 'UIGestureRecognizer'

Am I doing something wrong?

Error when run it in xcode 10.1

screenshot 2019-01-29 at 5 18 02 pm
This issue is occurs when i am running the demo code in xcode 10.1

Please give me solution on urgent base so i can use it.

Thanks

Memory leak

in ColorPickerThumbView
var delegate: LimitedGestureViewDelegate?
need add weak
weak var delegate: LimitedGestureViewDelegate?

Swift 5.2 complaint

Description:

  • Have no warning when compiling

  • Actual behaviour:
    Swift 5.2 included in Xcode Version 11.4 reports a warning:
    In UIImageExtension.swift
    let imageRect = CGRect(origin: .zero, size: size)

Initialization of immutable value 'imageRect' was never used; consider replacing with assignment to '_' or removing it

  • FlexColorPicker version: 1.3.1
  • Xcode version: Version 11.4.1

How to reproduce:

Integrate project

iOS 13 dark mode support

I noticed that the default background color of the view controllers is "white" and not "systemBackground"

RectangularPaletteControl has 'open' function but not declared is 'open'

Discussion: RectangularPaletteControl has 'open func setHue(horizontalAxis: Bool, updateImage: Bool)' but not declared as 'open' itself. So you cannot inherit from RectangularPaletteControl directly and you need to reimplement it's behaviour using ColorPaletteControl. If I will just copy-paste it's code there other things that is closed to override too. Or, for example, I want too use RectangularPaletteControl but override some open functions from ColorPaletteControl I cannot do that.

Suggestion: Make RectangularPaletteControl 'open' to inherit too.

SPM support

Would be great to have Swift Package Manager support

Add Hue slider

To be used with saturation slider as and alternative to hue-saturation palette.

Invalid Excludes when using with Xcode 13

When building using Xcode 13 the package is going warnings about the excludes listed in the package. Both podsec and the GifsAndScreenShots are being reported as not found. Looking at the paths in the DerivedData its looking as if the paths are slightly off on the actual location and what is trying to be excluded.

Put examples how to work with custom view via code.

Hi. Your library is so cool but the big issue that absolutely not clear to understand how use it in code. Can you add code examples how add custom elements on the layout via code. Pls don't link your Demo project, it's a lot of code, that not easy to read.

Unable to understand how to use the code

Sir i am very new to xcode and i am making an app where i must select the colour and get RGB values i am just able to add radial colour pallet and nothing more can you please brief me how to use

Unable to understand how to use the code

Sir i am very new to xcode and i am making an app where i must select the colour and get RGB values i am just able to add radial colour pallet and nothing more can you please brief me how to use

AutoLayout With ScrollView Crashing - iOS 15 Xcode 13

Hello,

It seems to crash no matter what constraints I set when adding the control to a scrollview that has auto layout.

Any suggestions? I will update this post with the crash stacktrace and a screenshot of my constraints.

Thanks
Joe

Support for alpha/semi-transparent colors

Add (optional) slider for alpha value/channel of picked color.

Checkboard-like backgorund should be added to color preview control to allow preview of transparency.

Showing Alpha value slider should become an option of DefaultColorPickerViewController (off by default).

Crash iOS15

I use a very simple color picker, just the default:

let colorPickerController = DefaultColorPickerViewController()
colorPickerController.delegate = self
colorPickerController.selectedColor = UIColor.init(hex: user.invoice_color_hex)
colorPickerController.navigationItem.title = "Settings_InvoiceLayout_HeadersColor".localized()
self.navigationController?.pushViewController(colorPickerController, animated: true)

It has always worked perfectly, until iOS15. It seems to crash on this line:

public var contentBounds: CGRect {
    layoutIfNeeded()
    return contentView.frame
}

//Previous functions before it arrived here

private func updateCornerRadius() {
    gradientBackgroundView.cornerRadius_ = contentBounds.height / 2
}
open override var bounds: CGRect {
    didSet {
        updateCornerRadius()
        updateThumbAndGradient(isInteractive: false)
    }
}

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.