UILabel subclass, which additionally allows shadow blur, inner shadow, stroke text and fill gradient.

Overview

THLabel

CocoaPods Compatible Carthage Compatible Platform Twitter

THLabel is a subclass of UILabel, which additionally allows shadow blur, inner shadow, stroke text and fill gradient.

THLabel screenshot

Requirements

  • iOS 4.0 or higher (below iOS 7.0 is untested though)
  • ARC enabled

Installation

The easiest way to use THLabel in your app is via CocoaPods.

  1. Add the following line in the project's Podfile file: pod 'THLabel', '~> 1.4.0'
  2. Run the command pod install from the Podfile folder directory.

Manual Installation

  1. Add CoreText.framework to your Link Binary with Libraries list.
  2. Drag these files into your project: THLabel.h, THLabel.m

IBDesignable / IBInspectable

There is an ibdesignable branch, if you're interested in this feature. It has been removed from the master branch, because IBDesignable and IBInspectable cause problems with CocoaPods, if you're not using use_frameworks! in your Podfile.

Usage

You can create THLabels programmatically, or create them in Interface Builder by dragging an ordinary UILabel into your view and setting its Custom Class to THLabel. With Xcode 6 you can set most of the properties within Interface Builder, which will preview your changes immediately.

Properties

Spacing

@property CGFloat letterSpacing;
@property CGFloat lineSpacing;

You can modify letter spacing of the text (also known as kerning) by changing the letterSpacing property. The default value is 0.0. A positive value will separate the characters, whereas a negative value will make them closer.

Modify line spacing of the text (also known as leading) by changing the lineSpacing property. The default value is 0.0. Only positive values will have an effect.

Shadow Blur

@property CGFloat shadowBlur;

Additionally to UILabel's shadowColor and shadowOffset, you can set a shadow blur to soften the shadow.

Inner Shadow

@property CGFloat innerShadowBlur;
@property CGSize innerShadowOffset;
@property UIColor *innerShadowColor;

The inner shadow has similar properties as UILabel's shadow, once again additionally with a shadow blur. If an inner shadow and a stroke are overlapping, it will appear beneath the stroke.

Stroke Text

@property CGFloat strokeSize;
@property UIColor *strokeColor;
@property THLabelStrokePosition strokePosition;

You can set an outer, centered or inner stroke by setting the strokePosition property. Default value is THLabelStrokePositionOutside. Other options are THLabelStrokePositionCenter and THLabelStrokePositionInside.

Fill Gradient

@property UIColor *gradientStartColor;
@property UIColor *gradientEndColor;
@property NSArray *gradientColors;
@property CGPoint gradientStartPoint;
@property CGPoint gradientEndPoint;

The gradient can consist of multiple colors, which have to be saved as UIColor objects in the gradientColors array. For more convenience, gradientStartColor and gradientEndColor will fill up the array accordingly.

The starting and ending points of the gradient are in the range 0 to 1, where (0, 0) is the top-left and (1, 1) the bottom-right of the text. The default value for gradientStartPoint is (0.5, 0.2) and for gradientEndPoint it is (0.5, 0.8).

Fade Truncating

@property THLabelFadeTruncatingMode fadeTruncatingMode;

You can fade in/out your label by setting the fadeTruncatingMode property. Default value is THLabelFadeTruncatingModeNone. The options are THLabelFadeTruncatingModeTail, THLabelFadeTruncatingModeHead and THLabelFadeTruncatingModeHeadAndTail.

Text Insets / Padding

@property UIEdgeInsets textInsets;
@property BOOL automaticallyAdjustTextInsets;

Effects like stroke and shadow can't be drawn outside of the bounds of the label view. You may need to set text insets to move a bit away from the edge so that the effects don't get clipped. This will be automatically done if you set automaticallyAdjustTextInsets to YES, which is also the default value.

Notes

THLabel respects (unlike UILabel) the contentMode property, which is used for vertical alignment. The textAlignment still has the higher priority, when it comes to horizontal alignment.

However THLabel doesn't respect the numberOfLines property, because Core Text doesn't support it natively. If you would like to have multiple lines, set lineBreakMode to NSLineBreakByWordWrapping.

THLabels are slower to draw than UILabels, so be aware of that.

Credits

Original source and inspiration from:

Big thanks to Jason Miller for showing me sample code of his implementation using Core Text! It inspired me to dig deeper and move away from drawing with NSAttributedString on iOS 7, which caused a lot of problems.

License

Distributed under the permissive zlib license. See the LICENSE file for more info.

Contact

Tobias Hagemann

Comments
  • Text Clipping

    Text Clipping

    Hi,

    I'm getting some clipping around the text with the font I'm using ios simulator screen shot 08-sep-2014 3 29 16 pm

    I updated the sizetofit method on THLabel but it removes the clipping only on the right hand side

    -(void)sizeToFit
    {
        [super sizeToFit];
        CGRect frame = self.frame;
        CGRect expandedFrame = CGRectInset(frame, -self.strokeSize * 2, -self.strokeSize *2);
        [self setFrame:expandedFrame];
        [self setNeedsDisplay];
    }
    

    ios simulator screen shot 08-sep-2014 3 34 07 pm

    The issue is only visible when using sizeToFit. I have faar to many labels to manually set the frames for them. Any suggestions?

    opened by superprat 19
  • Thin black outline around text

    Thin black outline around text

    If I render a white THLabel above a white background, you can see it adding a thin black line around the text. This also means that text rendered small will become thinner and disappear quicker than it should.

    screen shot 2014-10-16 at 10 57 55

    screen shot 2014-10-16 at 10 59 47

    screen shot 2014-10-16 at 10 58 51

    opened by jowie 8
  • crash with swift 3, xcode 8

    crash with swift 3, xcode 8

    I'm getting a strange crash in

    • (CTFrameRef)frameRefFromSize:(CGSize)size textRectOutput:(CGRect *)textRectOutput CF_RETURNS_RETAINED

    when I call it from the did set on text (I'm doing some logic in a subclass to provide better multi-line wrapping)

        override var text: String? {
            didSet {
                wrapText()
            }
        }
    

    it is a bad access at

    CFStringRef stringRef = (__bridge CFStringRef)self.text;

    I can fix it by replacing that with

        NSString *myString=self.text;
    
        CFStringRef stringRef = (__bridge CFStringRef)myString;
    

    I don't really understand what is happening here - but something memory related...

    opened by ConfusedVorlon 7
  • No way of getting bounding box for text

    No way of getting bounding box for text

    There is no way of generating a bounding box for the text given a fixed width, similar to NSAttributedString.boundingRect(with:options:context:)

    If you use NSAttributedString.boundingRect(with:options:context:), estimate is wrong and text ends up getting cut off.

    opened by sgil 4
  • Missing UIColor *shadowColor in .h

    Missing UIColor *shadowColor in .h

    I tried out THLabel because I needed a good way to handle shadows on labels. Apparently it was not working for me until I added UIColor *shadowColor to .h. Have you noticed this?

    @property (nonatomic, strong) IBInspectable UIColor *shadowColor;
    

    Edit: Using Xcode 6.1, iOS 7.0 project.

    opened by tropicdome 4
  • Potential memory leak on iOS 7 (xcode 5)

    Potential memory leak on iOS 7 (xcode 5)

    Hi,

    When I run Analyze I get a "THLabel.m:510:2: Potential leak of an object stored into 'image'" It is in inverseMaskFromAlphaMask the line - return image;

    Also there are similar warnings for: THLabel.m:543:2: Potential leak of an object stored into 'image' THLabel.m:583:2: Potential leak of an object stored into 'image'

    opened by boazin 4
  • EXC Bad Access on CTFrameSetter

    EXC Bad Access on CTFrameSetter

    I installed latest version via cocoa pods. I target iOS 9.0 and higher.

    This lines throws a EXC_BAD_ACCES error : CTFramesetterRef framesetterRef = CTFramesetterCreateWithAttributedString(attributedStringRef);

    Any idea why ?

    opened by AmbroiseCollon 3
  • Warning in XCode 7

    Warning in XCode 7

    THLabel.m line 430:

    CTTextAlignment alignment = NSTextAlignmentToCTTextAlignment ? NSTextAlignmentToCTTextAlignment(self.textAlignment) : [self CTTextAlignmentFromNSTextAlignment:self.textAlignment];

    gives a warning "Code will never be executed".

    Not really a problem, but I like to keep my code warning free, so might be worth fixing for people with similar needs.

    opened by margusholland 3
  • THLabel not fitting Label Box

    THLabel not fitting Label Box

    I have defined a THLabel programmatically as follows.

    THLabel *labelValue4 = [[THLabel alloc] initWithFrame:CGRectMake(20,269,300,85)]; labelValue4.text = @"Spectacular"; labelValue4.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size: 57.0]; labelValue4.textColor = [UIColor colorWithRed:52/255.f green:152/255.f blue:255/255.f alpha:1.0]; labelValue4.textAlignment = NSTextAlignmentLeft; labelValue4.numberOfLines = 1; labelValue4.backgroundColor = [UIColor clearColor]; labelValue4.strokeColor = [UIColor blackColor]; labelValue4.strokeSize = 1.0; [self.view addSubview:labelValue4];

    What I want is if the word is large like "spectacular" then it should adjust the size of the font automatically but it doesn't. It just chops off the word. How can I fix that? By the way really nice with THLabel. ios simulator screen shot sep 26 2014 5 47 47 pm

    Or I get this for labelValue4.text = @"Partly Cloudy"; dot dot dot ios simulator screen shot sep 26 2014 6 10 30 pm

    opened by sambudda 3
  • About Vertical alignment

    About Vertical alignment

    Hello, I used THLabel 1.0.3 and it works fine in my app. But after updating to THLabel 1.3.1, it has Chinese font vertical alignment problem. English font is normal . How can I solve this problem ? ios_simulator_screen_shot_2014 9 9 _ 8_31_33 ios_simulator_screen_shot_2014 9 9 _ 8_39_58

    opened by avocet 3
  • TH Label not compatible under iOs 6

    TH Label not compatible under iOs 6

    Hello,

    I may be wrong but in the requirements sections of THLabel i read "iOS 4.0 or higher" and I assumed it could be used on devices running on iOS 4, 5,... but the use in the code of NSTextAlignmentToCTTextAlignment makes the code crash on devices under iOs 6.

    Maybe it would be nice to just precise it on the description.

    Anyway the label is really nice , thanks, too bad does not work on iOs 5 =)

    Bye

    opened by Crabman 3
  • Solid stroke with outside positioning

    Solid stroke with outside positioning

    Hi!

    I'm trying to use THLabel to create a solid white background around my label that follows the shape of the text. It looks fine mostly, but some letters can cause holes in the stroke's shape, which makes it a bit ugly.

    The following image shows the problem with the letter 'i': IMG_EC9B0D7411C0-1

    And the desired output would be: IMG_2EB23E5F7DC1-1

    I've come up with a temporary solution, but it's probably not the most optimal. In the strokeImageWithRect function I've applied a 1px white shadow on the clipping mask, then used this idea to "remove" the opacity of the blurred shadow edges: https://stackoverflow.com/questions/14622202/can-cgcontextcliptomask-mask-all-non-transparent-pixels-with-alpha-1

    I wonder if there's any better way of filling the holes directly on the clipping mask's path, without using a shadow.

    opened by endanke 0
  • Support attributed string

    Support attributed string

    I used this label to display an attributed string but it did not work with underline or strike through. I tried to set stroke size to a large number without changing its bounds and recognized that there might be loss of text. How could I do to keep the content and number of lines if stroke size goes up?

    opened by dungntm58 0
  • THLabel swift

    THLabel swift

    Hi

    I had some free time and made swift version of you subclass. You can check it there https://github.com/IGRSoft/THLabel :branch => swift

    If you like it, you can make a swift branch and I'll make pull request :)

    Have a nice day ;)

    opened by iKorich 1
  • DrawRect is Extremely CPU intensive

    DrawRect is Extremely CPU intensive

    I used this label in a game that was running 60fps. My entire game update loop ran about 40% of the CPU at the my intense parts. THLabel ran at 14%. Those percentages are over a minute of gameplay with the THLabel changing its text once a second.

    I had to work around it with snapshots of THLabels for various words generated before the game starts.

    However, looking at the DrawRect briefly I see some places for speed improvements. It will likely never be fast enough for 60fps rendering as I know Core Text can be extremely expensive. But every little bit of CPU we can save means better battery life under normal operating conditions.

    As people fill this thread with ideas, I'll see if I can find time to implement a few.

    opened by EmperiorEric 1
Releases(1.4.10)
Owner
Tobias Hagemann
Co-founder & CEO of @skymatic • Developer & Designer • Working on @cryptomator
Tobias Hagemann
KDEDateLabel is an UILabel subclass that updates itself to make time ago's format easier.

KDEDateLabel KDEDateLabel is an UILabel subclass that saves you from refreshing it when using 'time ago' format. Installation You have multiple choice

Kevin Delannoy 117 May 16, 2022
A morphing UILabel subclass written in Swift.

LTMorphingLabel A morphing UILabel subclass written in Swift. The .Scale effect mimicked Apple's QuickType animation of iOS 8 of WWDC 2014. New morphi

Lex Tang 7.9k Jan 4, 2023
Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.

Atributika is an easy and painless way to build NSAttributedString. It is able to detect HTML-like tags, links, phone numbers, hashtags, any regex or

Pavel Sharanda 1.1k Dec 26, 2022
Animated Mask Label is a nice gradient animated label.

Animated Mask Label Demo Screen Screenshot Demo/Example For demo: $ pod try AnimatedMaskLabel To run the example project, clone the repo, and run pod

Jogendra 19 Dec 13, 2022
Simple countdown UILabel with morphing animation, and some useful function.

CountdownLabel Simple countdown UILabel with morphing animation, and some useful function. features Simple creation Easily get status of countdown fro

keishi suzuki 903 Dec 29, 2022
Incrementable UILabel for iOS and tvOS

IncrementableLabel IncrementableLabel is the easiest way to have incrementable numbers in an UILabel! Usage let myIncrementableLabel = IncrementableLa

Tom Baranes 81 Feb 4, 2022
A drop-in replacement for UILabel that supports attributes, data detectors, links, and more

TTTAttributedLabel A drop-in replacement for UILabel that supports attributes, data detectors, links, and more TTTAttributedLabel is a drop-in replace

TTTAttributedLabel 8.8k Dec 30, 2022
UILabel drop-in replacement supporting Hashtags

ActiveLabel.swift UILabel drop-in replacement supporting Hashtags (#), Mentions (@), URLs (http://), Emails and custom regex patterns, written in Swif

Optonaut 4.2k Dec 31, 2022
Glitching UILabel for iOS 📺

Glitching UILabel for iOS ?? Created by Lee Sun-Hyoup. Try the sample $ pod try GlitchLabel Requirements iOS 8.0+ Swift 3 Xcode 8 Installation CocoaP

Lee Sun-Hyoup 1k Dec 14, 2022
UILabel with image placed from left or right

SMIconLabel UILabel with possibility to place small icon on the left or on the right side. Take a look at preview image or build sample app to see how

Anatoliy Voropay 94 Apr 27, 2022
A handy class for iOS to use UILabel as a countdown timer or stopwatch just like in Apple Clock App.

MZTimerLabel Purpose MZTimerLabel is a UILabel subclass, which is a handy way to use UILabel as a countdown timer or stopwatch just like that in Apple

Mines Chan 1.6k Dec 14, 2022
UILabel replacement with fine-grain appear/disappear animation

ZCAnimatedLabel UILabel-like view with easy to extend appear/disappear animation Features Rich text support (with NSAttributedString) Group aniamtion

Chen 2.3k Dec 5, 2022
MTLLinkLabel is linkable UILabel. Written in Swift.

# MTLLinkLabel is linkable UILabel. Written in Swift. Requirements iOS 8.0+ Xcode 7.3+ Installation Carthage You can install Carthage with Homebrew. $

Recruit Holdings. Media Technology Lab 74 Jul 1, 2022
Adds animated counting support to UILabel.

UICountingLabel Adds animated counting support to UILabel. CocoaPods UICountingLabel is available on CocoaPods. Add this to your Podfile: pod 'UICount

Tim Gostony 1.9k Dec 1, 2022
Lightweight library to set an Image as text background. Written in swift.

Simple and light weight UIView that animate text with an image.

Lucas Ortis 552 Sep 9, 2022
Configurable morphing transitions between text values of a label.

TOMSMorphingLabel Configurable morphing transitions between text values of a label. Triggering the animation is as easy as setting the labels text pro

Tom König 1.9k Nov 20, 2022
Secret app like text animation

RQShineLabel A UILabel subclass that lets you animate text similar to Secret app. Installation CocoaPods RQShineLabel is available through CocoaPods,

gk 2k Dec 6, 2022
Custom Label to apply animations on whole text or letters.

Ophiuchus Custom Label to apply animations on whole text or letters. Check an article on our blog Inspired by this project on Dribble Installation Coc

Yalantis 885 Dec 2, 2022
Swift UIView for sliding text with page indicator

SlidingText for Swift Requirements Requires iOS 8 or later and Xcode 6.1+ Installation SlidingText is available through CocoaPods. To install it, simp

Dionysis Karatzas 53 Mar 1, 2022