A star rating control for iOS/tvOS written in Swift

Overview

Cosmos, a star rating control for iOS and tvOS

Carthage compatible CocoaPods Version Swift Package Manager compatible License Platform

Cosmos, star rating control for iOS / Swift

This is a UI control for iOS and tvOS written in Swift. It shows a star rating and takes rating input from the user. Cosmos is a subclass of a UIView that will allow your users to post those inescapable 1-star reviews!

  • Shows star rating with an optional text label.
  • Can be used as a rating input control (iOS only).
  • Cosmos view can be customized in the Storyboard without writing code.
  • Includes different star filling modes: full, half-filled and precise.
  • Cosmos is accessible and works with voice-over.
  • Supports right-to-left languages.

Binary star system of Sirius A and Sirius B (artist's impression)

Picture of binary star system of Sirius A and Sirius B by NASA, ESA and G. Bacon (STScI). Source: spacetelescope.org.

Video tutorial

Thanks to Alex Nagy from rebeloper.com for creating this amazing video tutorial that shows how to use and customize Cosmos from code.

Cosmos rating video tutorial for Swift 4.2 (Xcode10)

Setup

There are various ways you can add Cosmos to your Xcode project.

Add source (iOS 8+)

Simply add CosmosDistrib.swift file into your Xcode project.

Setup with Carthage (iOS 8+)

Alternatively, add github "evgenyneu/Cosmos" ~> 23.0 to your Cartfile and run carthage update.

Setup with CocoaPods (iOS 8+)

If you are using CocoaPods add this text to your Podfile and run pod install.

use_frameworks!
target 'Your target name'
pod 'Cosmos', '~> 23.0'

Setup with Swift Package Manager

Legacy Swift versions

Setup a previous version of the library if you use an older version of Swift.

Usage

  1. Drag View object from the Object Library into your storyboard.

Add view control in attributes inspector

  1. Set the view's class to CosmosView in the Identity Inspector. Set its module property to Cosmos, unless you used the file setup method.

Add Cosmos rating view to the storyboard

tvOS note: read the collowing setup instructions for tvOS if you see build errors at this stage.

  1. Customize the Cosmos view appearance in the Attributes Inspector. If storyboard does not show the stars click Refresh All Views from the Editor menu.

Customize cosmos appearance in the attributes inspector in Xcode.

Positioning the Cosmos view

One can position the Cosmos view using Auto Layout constaints. The width and height of the view is determined automatically based on the size of its content - stars and text. Therefore, there is no need to set width/height constaints on the Cosmos view.

Using Cosmos in code

Add import Cosmos to your source code, unless you used the file setup method.

You can style and control Cosmos view from your code by creating an outlet in your view controller. Alternatively, one can instantiate CosmosView class and add it to the view manually without using Storyboard.

// Change the cosmos view rating
cosmosView.rating = 4

// Change the text
cosmosView.text = "(123)"

// Called when user finishes changing the rating by lifting the finger from the view.
// This may be a good place to save the rating in the database or send to the server.
cosmosView.didFinishTouchingCosmos = { rating in }

// A closure that is called when user changes the rating by touching the view.
// This can be used to update UI as the rating is being changed by moving a finger.
cosmosView.didTouchCosmos = { rating in }

Customization

One can customize Cosmos from code by changing its settings. See the Cosmos configuration manual for the complete list of configuration options.

// Do not change rating when touched
// Use if you need just to show the stars without getting user's input
cosmosView.settings.updateOnTouch = false

// Show only fully filled stars
cosmosView.settings.fillMode = .full
// Other fill modes: .half, .precise

// Change the size of the stars
cosmosView.settings.starSize = 30

// Set the distance between stars
cosmosView.settings.starMargin = 5

// Set the color of a filled star
cosmosView.settings.filledColor = UIColor.orange

// Set the border color of an empty star
cosmosView.settings.emptyBorderColor = UIColor.orange

// Set the border color of a filled star
cosmosView.settings.filledBorderColor = UIColor.orange

Supplying images for the stars

By default, Cosmos draws the stars from an array of points. Alternatively, one can supply custom images for the stars, both in the Storyboard and from code.

Using star images from the Storyboard

Supplying an image for a star in Xcode.

Using star images from code

// Set image for the filled star
cosmosView.settings.filledImage = UIImage(named: "GoldStarFilled")

// Set image for the empty star
cosmosView.settings.emptyImage = UIImage(named: "GoldStarEmpty")

Note: you need to have the images for the filled and empty star in your project for this code to work.

Download star image files

Images for the golden star used in the demo app are available in here. Contributions for other star images are very welcome: add vector images to /graphics/Stars/ directory and submit a pull request.

Using Cosmos in a scroll/table view

Here is how to use Cosmos in a scroll view or a table view.

Using Cosmos with SwiftUI

Here is how to show a Cosmos view with SwiftUI.

Using Cosmos in a modal screen

iOS 13 introduced swiping gesture for closing modal screens, which prevents Cosmos from working properly. The following setting fixes this problem:

cosmosView.settings.disablePanGestures = true

Using Cosmos settings from Objective-C

This manual describes how to set/read Cosmos settings in Objective-C apps.

Demo app

This project includes a demo iOS app.

Five star rating control for iOS written in Swift

Using cosmos in a table view

Using cosmos in a table view

Alternative solutions

Here are some other star rating controls for iOS:

Thanks πŸ‘

We would like to thank the following people for their valuable contributions.

  • jsahoo for adding ability to customize the Cosmos view from the interface builder with Carthage setup method.
  • 0x7fffffff for changing public access-level modifiers to open.
  • ali-zahedi for updating to the latest version of Swift 3.0.
  • augmentedworks for adding borders to filled stars.
  • craiggrummitt for Xcode 8 beta 4 support.
  • JimiSmith for Xcode 8 beta 6 support.
  • nickhart for adding compatibility with Xcode 6.
  • staticdreams for bringing tvOS support.
  • wagnersouz4 for Swift 3.1 update.
  • paoloq for reporting the CosmoView frame size issue when the view is used without Auto Layout.
  • danshevluk for adding ability to reuse settings in multiple cosmos views.
  • xrayman for reporting a table view reusability bug and improving the table view screen of the demo app.
  • chlumik for updating to Swift 4.2.
  • rebeloper for creating a video tutorial.
  • yuravake for adding passTouchesToSuperview setting.
  • gcharita for adding Swift Package Manager support.
  • benpackard for fixing Cosmos when used in a modal screen on iOS 13.
  • dkk for the dark mode update.

License

Cosmos is released under the MIT License.

🌌 ⭐️ πŸŒ• πŸš€ 🌠

We are a way for the cosmos to know itself.

Carl Sagan, from 1980 "Cosmos: A Personal Voyage" TV series.

Comments
  • CosmosView not updating to touch events in ScrollView

    CosmosView not updating to touch events in ScrollView

    I have a ScrollView -> View -> CosmosView. All UserInteractionEnabled properties are ON. I can change the rating on the stars by swiping easily, but tapping on them is very hard. Maybe is because the tap events are not well handled here, i don't know, but all config of the scrollview and view are by default. Any help? https://s10.postimg.org/nkklw7rrd/Screen_Shot_2016_08_09_at_11_24_29_AM.png

    opened by SlavcoPetkovski 24
  • Compilation error

    Compilation error

    Hello, using last Xcode version and iOS 11. That error message:

    /Users/dylandivito/hairdresserios/Hairdresser/Pods/Cosmos/Cosmos/CosmosLayerHelper.swift:17:43: Incorrect argument label in call (have 'withAttributes:', expected 'attributes:')

    That call seems completely deprecated

    https://puu.sh/xKTww/07b4f54e6e.png

    Could you fix this please ?

    opened by yamakhalah 14
  • Xcode 12 'IPHONEOS_DEPLOYMENT_TARGET' warning

    Xcode 12 'IPHONEOS_DEPLOYMENT_TARGET' warning

    Please consider submitting the following information (if relevant):

    The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.0.99.

    • CocoaPods
    • Version of the library. 21.0.0
    • Xcode version. 12.0
    • OS version. iOS 14
    opened by gilrodar 12
  • Not supporting Swift 4

    Not supporting Swift 4

    • Version of the library: 12.0.1
    • Xcode version: 9.1
    • OS version: 10.12.6

    CosmosLayerHelper -> Line#17 -> let size = NSString(string: text).size(withAttributes: [NSAttributedStringKey.font: font])

    it should be-> let size = NSString(string: text).size(attributes: [NSAttributedStringKey.font: font])

    Please fix it ASAP.

    opened by randhirkumarcse 11
  • Unable to select more than 5 stars with default size settings

    Unable to select more than 5 stars with default size settings

    I set 6 total stars and a star size of 30.0, in this way I cannot select more than 4 stars. Setting 6 total star and the default star size, I cannot select more than 5 stars. Seems like the touchable area remains always at the default size, not updating once the drawn area changed.

    opened by paoloq 11
  • Error when load it to TableView

    Error when load it to TableView

    I drag a view and set its class to CosmosView, but when I run the project, it crashes:

    Failed to set (rateLineWidth) user defined inspected property on (Cosmos.CosmosView): [<Cosmos.CosmosView 0x7ff150d53e70> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key rateLineWidth.

    opened by khuong291 11
  • Please help add view in code

    Please help add view in code

    Could you please help me how to write the code to add Cosmos without storyboard? I need a row with a variable amount of cosmos UIViews depending on the size of an array.

    I did not understand how you meant this: "Alternatively, one can instantiate CosmosView class and add it to the view manually without using Storyboard."

    Thank you very much in advance!!

    opened by andreichirkunovgoon 11
  • Cosmos on UITableViewCell

    Cosmos on UITableViewCell

    How can we use Cosmos Star on UITableViewCell , since my requirement is to get multiple rating stars to rate on specific cell index and send to server

    opened by rupeshsaxena 11
  • First touch in collectionView

    First touch in collectionView

    • Library setup method:CocoaPods
    • Version of the library. last version
    • Xcode version.: 11.7
    • OS version.: iOS 13

    Hi, When cosmos inside collectionViewCell scrolling is not working properly. because when i start scrolling at the collectionview's random point, it is working. But when my first touch position is on the cosmosView, scroll is not working. After that my touches triggered cosmosView unless rating is finished. I want to cosmosView only trigger by horizontal touches or single taps. Any suggestions?

    πŸ‘πŸΌ ln the meantime, thank you so much for your attention and participationπŸ‘πŸΌ

    opened by oguzveozturk 10
  • Issue Cosmos in TableViewCells

    Issue Cosmos in TableViewCells

    Please consider submitting the following information (if relevant):

    • Library setup method: CocoaPods.
    • Version of the library. current
    • Xcode version. Example: current
    • OS version. Example: current.

    I have a problem where I have a cosmos view inside some tableviewcells, the problem is when I set rating the didSelectRow methos gets called and because of my app, another view controller is presented, I tried removing the listen of touch within the cell of the specific cosmos view but then the user interaction become disabled.

    Sorry for bad english.

    Do you have any idea of how can I solve this?

    Thank you.

    opened by abraham28s 10
  • Right To Left Support

    Right To Left Support

    Hi, first of all i'd like to thank you for this framework but i have a question . i there any plane for this framework to support right to left languages ?

    enhancement 
    opened by tarek903 10
  • Error While installing pod.

    Error While installing pod.

    Please consider submitting the following information (if relevant):

    • Library setup method: CocoaPods
    • Version of the library: 23.0.
    • Xcode version: 12.5
    • OS version: iOS 11.4 Screenshot 2021-06-25 at 4 06 31 PM
    opened by Jaydip2711 1
  • My image and `withTintColor`

    My image and `withTintColor`

    Hello, evgenyneu Thank you for your pod) I've got some question here. I have image in png format. I'm able to change tint of it in casual UIImageView with help of .withTintColor(_:) as it expected, but when I add image to rateView.settings.filledImage or rateView.settings.emptyImage with this method nothing happens. It adds my image with origin tint color. Is that supposed to be like that or kinda bug? How can I change tint color of added image in your pod?

    And one more question: Is it possible to change alignment of stars? Default statement like on left side. Can I make all stars aimed on center in my view?

    Sincerely, Andrew

    • Library setup method: CocoaPods
    • Version of the library: 23.0
    • Xcode version. 12.0
    • OS version. Example: 13.0
    opened by matsota-huma 2
  • Unwanted behavior in a UIScrollView

    Unwanted behavior in a UIScrollView

    When I put a CosmosView into a UIScrollView, here's how it responds to touches:

    • With disablePanGestures == false, when I touch and move horizontally, the stars are being updated as expected. But as soon as I move slightly vertically, UIScrollView's pan gesture detector captures the touch gesture and CosmosView acts as if the touch ended.
    • With disablePanGestures == true, there's a different problem when I just want to scroll and start by touching the CosmosView - it will immediately capture the touch gesture.

    Ideally, it should behave like UIButton does: when I touch and immediatelly start moving vertically, UIScrollView gets the gesture. Otherwise, the UIButton gets it.

    Here's how it can be done by extending CosmosView. The idea is that UIScrollView's pan detector is disabled only after CosmosView starts receiving touches, which by default happens after short delay, during which the UIScrollView has a chance to recognize a pan gesture.

    class MyCosmosView: CosmosView {
      open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.settings.disablePanGestures = true
        super.touchesBegan(touches, with: event)
      }
    
      open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.settings.disablePanGestures = false
        super.touchesEnded(touches, with: event)
      }
    
      open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.settings.disablePanGestures = false
        super.touchesCancelled(touches, with: event)
      }
    }
    
    
    opened by fhucho 4
  • Storyboard warning on Xcode 12.1:

    Storyboard warning on Xcode 12.1: "Ignoring user defined runtime attribute for key path "updateOnTouch""

    Please consider submitting the following information (if relevant):

    • Library setup method: Swift Package Manager.
    • Version of the library. 23.0
    • Xcode version. Example: 12.1 GM
    • OS version. Example: iOS 14.1

    Hi there, I just updated my project to Xcode 12.1, and I've started to get a build warning from a usage of Cosmos which was previously fine:

    BookDetails.storyboard: warning: IB Designables: Ignoring user defined runtime attribute for key path "updateOnTouch" on instance of "UIView". Hit an exception when attempting to set its value: [<UIView 0x7fb0cd5d31f0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key updateOnTouch.

    image

    image

    It reports that a build failed within the IBDesignable view in a storyboard, but when I actually build and run the app it works fine.

    opened by AndrewBennet 3
Owner
Evgenii Neumerzhitckii
πŸ‹πŸ¦”πŸ’πŸwow
Evgenii Neumerzhitckii
An emoji-liked rating view for iOS, implemented in Swift3.

TTGEmojiRate An emoji-liked rating view for iOS, implemented in Swift3. Android version: PeterSmileRate by SilicorniO. Great work ! :) Inspired by Rat

zekunyan 289 Jun 13, 2022
A simple and configurable rating/favorite view.

ImageRating A simple and configurable rating/favorite view. ImageRating will display a sequence of SFSymbols from 0-maxImages in half or whole increme

Ferdinand G Rios 0 Dec 24, 2021
Whole, half or floating point ratings control written in Swift

FloatRatingView A simple rating view for iOS written in Swift! Supports whole, half or floating point values. I couldn't find anything that easily set

Glen Yi 546 Dec 8, 2022
StarryStars is iOS GUI library for displaying and editing ratings

StarryStars StarryStars is iOS GUI library for displaying and editing ratings Features StarryStars' RatingView is both IBDesignable and IBInspectable

Peter Prokop 175 Nov 19, 2022
A modern utility that reminds your iOS app's users to review the app in a non-invasive way.

SiriusRating A modern utility that reminds your iOS app's users to review the app in a non-invasive way. Features SwiftUI and UIKit support Configurab

The App Capital 5 Sep 24, 2022
Simple star rating view for iOS written in Objective-C

HCSStarRatingView HCSStarRatingView is a UIControl subclass to easily provide users with a basic star rating interface. It supports all device resolut

Hugo Sousa 1.3k Dec 21, 2022
A simple star rating library for SwiftUI apps on macOS and iOS

DLDRating A simple star rating library for SwiftUI apps on macOS and iOS. Features Installation Usage Styling Credits DLDRating was made by Dionne Lie

null 1 Mar 6, 2022
RCalendarPicker A date picker control, Calendar calendar control, select control, calendar, date selection, the clock selection control.

RCalendarPicker RCalendarPicker Calendar calendar control, select control, calendar, date selection, the clock selection control. ζ—₯εŽ†ζŽ§δ»Ά ,ζ—₯εŽ†ι€‰ζ‹©ζŽ§δ»ΆοΌŒζ—₯εŽ†οΌŒζ—₯ζœŸι€‰ζ‹©

ζœθ€€θΎ‰ 131 Jul 18, 2022
An emoji-liked rating view for iOS, implemented in Swift3.

TTGEmojiRate An emoji-liked rating view for iOS, implemented in Swift3. Android version: PeterSmileRate by SilicorniO. Great work ! :) Inspired by Rat

zekunyan 289 Jun 13, 2022
Flix is a film rating application for iOS.

Flix is a film rating application for iOS.

Yijie Guo 0 Nov 20, 2021
A simple and configurable rating/favorite view.

ImageRating A simple and configurable rating/favorite view. ImageRating will display a sequence of SFSymbols from 0-maxImages in half or whole increme

Ferdinand G Rios 0 Dec 24, 2021
Control Room : a macOS app that lets you control the simulators for iOS, tvOS, and watchOS

Control Room is a macOS app that lets you control the simulators for iOS, tvOS, and watchOS – their UI appearance, status bar configuration, and more.

null 0 Nov 30, 2021
iOS App that browse the people from Star Wars Universe using GraphQL Api.

Ravn-Challenge-V2--OscarCastillo- iOS App that browse the people from Star Wars Universe using GraphQL Api. This project uses Apollo swift Client. htt

Oscar Castillo 4 Jun 9, 2021
Lambton College, 2nd Semester Final IOS Project (Star Wars) game

The game we developed for our project of the course advanced iOS application is based on a functioning of a real time shooting game, in which initiall

Suraj Devgan 6 Aug 18, 2022
Fetch the star wars api from all the planets and list and show details using Swift UI and Combine

Star Wars Planets Fetch the star wars planet data by using stat war api, list and show details using SwiftUI and Combine frameworks ?? Swift UI Framew

null 1 Aug 10, 2022
A Star Wars themed card game designed to see if you know your sith vs jedi

StarWarsCardGame A Star Wars themed card game designed to see if you know your sith vs jedi. Learning Objectives: Alert Controllers, Protocol/Delegate

Jonathan Llewellyn 0 Nov 29, 2021
:star: Custom card-designed CollectionView layout

CardsLayout CardsLayout is a lightweight Collection Layout. Installation CocoaPods You can use CocoaPods to install CardsLayout by adding it to your P

Filipp Fediakov 798 Dec 28, 2022
This sample app use the Star Wars public api to show a list of characters

StarWars-MVVM In this sample app, I use the Star Wars public api to show a list of characters from the Star Wars movie series. There are two goals I w

Paul O'Neill 1 Mar 8, 2022
Instant font size adjustment with control – / control +

Plugins manipulating UI (like this one) are not supported by Xcode 8 UPDATE: to avoid conflict with Interface Builder hotkeys are changed to Control -

Sash Zats 271 Jul 30, 2022
Fast Swift Views layouting without auto layout. No magic, pure code, full control and blazing fast. Concise syntax, intuitive, readable & chainable. [iOS/macOS/tvOS/CALayer]

Extremely Fast views layouting without auto layout. No magic, pure code, full control and blazing fast. Concise syntax, intuitive, readable & chainabl

layoutBox 2.1k Dec 22, 2022