Git Product home page Git Product logo

rtlabel's Introduction

RTLabel

Rich text formatting based on HTML-like markups for iOS.

RTLabel works like UILabel, but supports html-like markups for rich text display. It is based on Core Text, so it supports some of the stuff that Core Text supports

Features

  • bold and italic style
  • color and size
  • stroke
  • indenting
  • kerning
  • line spacing
  • clickable links

Usage

  1. Drag RTLabel.h and RTLabel.m into your project. Import CoreText framework

    #import "RTLabel.h"

  2. Create RTLabel

    NSString *sample_text = @"bold,italic and underlined text, and text with custom font and color";

    RTLabel *label = [[RTLabel alloc] initWithFrame:...]; [self addSubview:label]; [label setText:sample_text];

  3. Supports the following tags

    Bold Italic Bold & Italic underline, underline with color link double underline , double underline with color custom font custom font with strokes custom font with kerning

    alignment

    indentation

Minimum Requirements

  • ARC - this project uses ARC. If you are not using ARC in your project, add '-fobjc-arc' as a compiler flag for StyledPageControl.h and StyledPageControl.m
  • Xcode 4.4 and newer (auto-synthesis required)

Contact

twitter.com/honcheng
honcheng.com

rtlabel's People

Contributors

argentini avatar danielebogo avatar days avatar devinross avatar epatel avatar epologee avatar honcheng avatar jameshays avatar jonreid avatar kashifsoofi avatar kdaker avatar kenvanhoeylandt avatar readmecritic avatar sbandol avatar susieyy 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  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

rtlabel's Issues

Slow rendering with large HTML strings

Implementing RTLabel in a UITableView with a UITableViewCell, the table get stucks when I scroll and the cells appears The cell needs a little time to render the view, because de HTML texts are sometimes large.

Any ideas to improve it?

Multiline links

Heya, I've been playing around with the RTLabel, and I'm having a few troubles involving multiline links. Firstly, the optimumSize seems to not compute correctly if a link spans multiple lines, and also the hit testing when tapping links does not work below the first line of the link.

Have you encountered this before? Would you know how to make a workaround?

Cheers,
Eric-Paul.

Calculate Size

Hi honcheng,

first of all i want to thank you about this amazing label you give us.

I'm using RTLabel in my new app, everything is cool, great features, nice behavior...

I only have one thing that is making me lose my mind : how to calculate the size of the RTLabel depending on NSString ?

I use a CGConstraint to calculate the height of the label based on the RTLabel's text (NSString) but sometimes it is longer, sometimes shorter... can't have the real size.

How can i do this ?

thanks.

Ps : maybe you should add a donation button using paypal.

Intrinsic content size information

When using AutoLayout and building a UIView that contains one or various RTLabel, if you want the size of the UIView to depends on the size of the RTLabel, the RTLabel class needs to be extended in order to override the intrinsicContentSize function to return [self optimumSize].

It would be nice to have this feature added by default in the RTLabel class.

Truncation with "..." of multiple line label

I've tried to understand this, and from what I can google, this is not the easiest thing. This is more like a question than an issue. Are you looking into this? Because it would really be a nice feature. I´ll look into it too, but I am really new to Core Text and it all seems quite complicated.

Set line spacing

Hello, I'm ios developer. I have a problem with line spacing. I use font that not a system font. It has a height line spacing :( I want to know "How to set line spacing?"
Thank you.

Memory leak in render

frame in render is not release, causing critical memory leak.
frame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0, 0), path, NULL);

[RTLabel render] Cash on CFAttributedStringSetAttributes

I'm trying to use this great Library. But my app crash into [RTLabel render] on line 206
CFAttributedStringSetAttributes( attrString, CFRangeMake( 0, CFAttributedStringGetLength(attrString) ), styleDict1, 0 );

Is this a well known bug ? I'm I doing something wrong ?

Thanx for the help !

try/catch block doesn't prevent bad HTML syntax

I wrap the only setText call in a standard @try/@catch block but it does not prevent the app from crashing because of bad HTML syntax. I can't prevent this, because data is coming from user.

In this case I have #FFFFF as the color code (missing one character).

How should i wrap the call so that it raises exception normally?

attribute check caused crash

if i wanna display some words like this : <a> tag provides links in a web page.

RTLabel.m , render function , about line 263 ,the function will check attribute "href" , but my text miss it.

maybe project can support < instead of < etc.

Getting rid of `CGContextSetTextMatrix: invalid context`

Because you use the render method from outside drawRect, e.g. to determine the optimumSize, the RTLabel class causes a lot of runtime errors like CGContextSetTextMatrix: invalid context.

You can fix this by changing the -(void)render method to pass a context, like -(void)render:(CGContextRef)context and then either call [self render:UIGraphicsGetCurrentContext()]; from within the drawRect or [self render:NULL]; from the other places.

That'd change your API a bit, but it takes care of the warnings.

Like the class, thanks for all the hard work that you put into it!
Cheers,
EP.

memory leak

1.run with profile,time profiler shows it may have memory leak
2.it cost much time in render

duplicated text inside uiscrollview

I added a rtlabel to a uiscrollview and when i scroll i have the text fixed on background and another copy of the text scrolling properly..

what can it be?

Newly initialized RTLabel hangs when using setText:

A newly initalized RTLabel isn't able to properly use setText:, because the textColor and font are not set. The result is that it hangs in the method render: at the lines 261 and 268 respectively.

Upon initialization, it should probably use a default font and color, to avoid this.

Default font...

When loading RTLabel instance from a XIB file, the font is nil. This causes the render method to fail.

Looks like the initWithCoder method is missing.

string range limits

I create a new project test a string like this
NSString * strDianJia=@"ikea</font>";
it runs to crash.but it works fine in your sample project.
I debuged.find in RTLabel.m file.
int position = [data rangeOfString:delimiter].location;
in my project the position return -1,if not find
so if (position!=NSNotFound) still true,but in your sample project it turns out to false.
I don't know why. so I set to false if it returns -1.

Crashes while using different font style

Hi,

I am using Varela Round font through out my project. I downloaded this library and added the VarelaRound-Regular.ttf to the resource folder , included "VarelaRound-Regular.ttf" to the info.plist file under font category.

I tried the following code
NSMutableDictionary *row2 = [NSMutableDictionary dictionary];
[
screen shot 2015-07-11 at 9 26 38 am
row2 setObject:@"underlined text" forKey:@"text"];
[self.dataArray addObject:row2];
running this crashes.

The log i get is
RTLabelProject[3300:70377] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString replaceOccurrencesOfString:withString:options:range:]: Range {0, 1} out of bounds; string length 0'

Crashing memory leak

I keep on getting this kind of crash. When I use the code provided in the sample it works fine but when I try to make my own, it crashes all the time. The crash log is;

[GSFont release]: message sent to deallocated instance

My UITableViewCell subclass are very simple. I dont know what is wrong here.

#import <UIKit/UIKit.h>
#import "RTLabel.h"
#define FROM_IMAGE_VIEW CGRectMake(8,8,32,32)
#define FROM_LABEL CGRectMake(48, 8, 320 - 48 - 16 - 8 - 8, 32)
#define SOURCE_ICON CGRectMake(320 - 8 - 16, 14, 16,16)
#define CUTLINE_IMAGE_VIEW CGRectMake(0, 8+32+8, 320, 1)
#define MESSAGE_LABEL CGRectMake(8,8+32+8+1+8, 320 - 8 - 8, 32)
#define TARGET_IMAGE_VIEW CGRectMake(8,8+32+8+1 + 8 + 32 + 8, 320 - 8 - 8 - 100, 90)
#define CAPTION_LABEL CGRectMake(8,8+32+8+1+ 8 + 32 + 8 + 90 + 8, 320 - 8 - 8, 32)
@interface Cell : UITableViewCell
@property(nonatomic, strong) UIImageView *fromImageView;
@property(nonatomic, strong) RTLabel *fromLabel;
@property(nonatomic, strong) RTLabel *messageLabel;
@property(nonatomic, strong) UIImageView *sourceIcon;
@property(nonatomic, strong) UIImageView *targetImageView;
@property(nonatomic, strong) RTLabel *captionLabel;
@property(nonatomic, strong) UIImageView *cutlineImageView;
@end
#import "Cell.h"

@implementation Cell
@synthesize fromImageView;
@synthesize fromLabel;
@synthesize messageLabel;
@synthesize sourceIcon;
@synthesize captionLabel;
@synthesize targetImageView;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){
        self.fromLabel = [self from];
        self.fromLabel.font = [UIFont boldSystemFontOfSize:13];
        self.fromLabel.backgroundColor = [UIColor clearColor];
        self.fromImageView = [[UIImageView alloc] initWithFrame:FROM_IMAGE_VIEW];
        self.messageLabel = [self message];
        self.messageLabel.backgroundColor = [UIColor clearColor];
        self.messageLabel.font = [UIFont boldSystemFontOfSize:13];
        [self.messageLabel setParagraphReplacement:@""];
        self.sourceIcon = [[UIImageView alloc] initWithFrame:SOURCE_ICON];
        self.captionLabel = [self caption];
        self.captionLabel.backgroundColor = [UIColor clearColor];
        self.captionLabel.font = [UIFont boldSystemFontOfSize:13];
        [self.captionLabel setParagraphReplacement:@""];
        self.targetImageView = [[UIImageView alloc] initWithFrame:TARGET_IMAGE_VIEW];
        [self.contentView addSubview:self.fromLabel];
        [self.contentView addSubview:self.fromImageView];
        [self.contentView addSubview:self.messageLabel];
        [self.contentView addSubview:self.sourceIcon];
        [self.contentView addSubview:self.captionLabel];
        [self.contentView addSubview:self.targetImageView];
        [self.contentView setBackgroundColor:[UIColor lightGrayColor]];
    }
    return self;
}

- (RTLabel*)from
{
    RTLabel *label = [[RTLabel alloc] initWithFrame:FROM_LABEL];
    [label setParagraphReplacement:@""];
    return label;
}
- (RTLabel*)message
{
    RTLabel *label = [[RTLabel alloc] initWithFrame:MESSAGE_LABEL];
    [label setParagraphReplacement:@""];
    return label;
}

- (RTLabel*)caption
{
    RTLabel *label = [[RTLabel alloc] initWithFrame:CAPTION_LABEL];
    [label setParagraphReplacement:@""];
    return label;
}
@end

Don't underline links

Hello,
is it possible to make a link not underlined? I don't want to modify the component itself, so I'm looking for another solution.

Best regards
Benny

optimumSize

optimumSize crashes, with: code=EXC_ARM_BREAKPOINT, subcode=0xdefe

label content is: "ENERGIEWENDE IN DEUTSCHLAND"
Here is the code (sorry for junk code):

           RTLabel *tv = [[RTLabel alloc] init];
                if([contentElement attributeNamed:@"line-height"]){
                    [tv setLineSpacing:[[contentElement attributeNamed:@"line-height"] floatValue]];
                }
                [tv setText:[contentElement value]];
                if([contentElement attributeNamed:@"line-height"]){
                    [tv setLineSpacing:[[contentElement attributeNamed:@"line-height"] floatValue]];
                }
                [tv setTag:[[contentElement attributeNamed:@"id"] intValue]];
                [tv setTranslatesAutoresizingMaskIntoConstraints:NO];

                UIFont *font;
                if(fontName && [contentElement attributeNamed:@"size"]){
                    font = [UIFont fontWithName:fontName size:[[contentElement attributeNamed:@"size"] intValue]];
                }else{
                    font = [UIFont fontWithName:fontName size:16];
                }
                [tv setFont:font];

                if([[contentElement attributeNamed:@"align"] isEqualToString:@"left"]){
                    tv.textAlignment = NSTextAlignmentLeft;
                }else if([[contentElement attributeNamed:@"align"] isEqualToString:@"right"]){
                    tv.textAlignment = NSTextAlignmentRight;
                }else{
                    tv.textAlignment = NSTextAlignmentLeft;
                }
                if([contentElement attributeNamed:@"color"]){
                    unsigned result = 0;
                    NSScanner *scanner = [NSScanner scannerWithString:[contentElement attributeNamed:@"color"]];
                    [scanner scanHexInt:&result];
                    UIColor *color = UIColorFromRGB(result);
                    if(invertedColors){
                        [tv setTextColor:[color inverseColor]];
                    }else{
                        [tv setTextColor:color];
                    }
                }else{
                    if(invertedColors){
                        [tv setTextColor:[UIColor whiteColor]];
                    }else{
                        [tv setTextColor:[UIColor blackColor]];
                    }
                }

                [tv setBackgroundColor:[UIColor clearColor]];
                tv.lineBreakMode = NSLineBreakByWordWrapping; // or some other desired wrapping

                if(width == 350){
                    CGRect frame = CGRectMake(0, 0, 350 - [[pageContent attributeNamed:@"margin"] floatValue], 9999); // oversized height
                    tv.frame = frame;
                }else{
                    CGRect frame = CGRectMake(0, 0, 1024, 9999); // oversized height
                    tv.frame = frame;
                }


                [containerView addSubview:tv];
                CGSize optimumSize = [tv optimumSize];

reason: '-[__NSCFString replaceOccurrencesOfString:withString:options:range:]: Range {0, 6} out of bounds; string length 2'

我遇到这个问题,i find the reason lies on RTLabel.m—— line 848~858:
if (position!=NSNotFound)
{
if ([delimiter rangeOfString:@"<p"].location==0)
{
data = [data stringByReplacingOccurrencesOfString:delimiter withString:paragraphReplacement options:NSCaseInsensitiveSearch range:NSMakeRange(last_position, position+delimiter.length-last_position)];
}
else
{
data = [data stringByReplacingOccurrencesOfString:delimiter withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(last_position, position+delimiter.length-last_position)];
}

        data = [data stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
        data = [data stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    }

How can i resolve it?THANKS!

Problem with unicode characters

When one of the characters in the string is a unicode character (in my case Hebrew character) so when I do:

[rtLabel setText:string];

The label doesn't get any text.

here is an example for the text input:
14א

resizing the RTLabel (eg. when the screen rotates) stretches the text

if you resize the RTLable when the screen rotates, the text gets stretched.
this can be reproduced by replacing the textLabel in the DemoTableViewCell.m with the one below (that adds the autoreszing masks then rotate the device when running the demo app).
Anyone know how to fix?

  • (RTLabel*)textLabel
    {
    RTLabel *label = [[RTLabel alloc] initWithFrame:CGRectMake(10,10,300,100)];
    //[label setFont:[UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:20]];
    [label setParagraphReplacement:@""];
    label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight |UIViewAutoresizingFlexibleBottomMargin;
    return label;
    }

Analyzer shows minor memory issues

If you compile the application using the Xcode4 analyzer, a few memory issues crop up:

RTLabel.m:applyParagraphStyleToText leaks styleDict

RTLabel.m:applyColor releases rgbColorSpace before using it.

RTLabel.m:applyUnderlineColor releases rgbColorSpace before using it.

Also, RTLabel.m:initWithTag gives a warning if warning levels are turned up. No big deal, but we always keep warnings high. I changed if (self = [super init]) to if ( (self = [super init]) != nil )

Thanks,
Eric Shapiro

crash when using underline tag <u>

Crash on line 280 in -(void)render in RTLabel.m:

    if ((component.attributes)[@"color"])

crashing with message:

    -[__NSDictionaryM retain]: message sent to deallocated instance 

the crash occurs when using a normal <u> tag without any colors or any additional options.

issue showing special character (' " &)

Hi

I am facing problem that RTLabel not able to show the single inverted qomma('), double inverted qomma(") and amp(&)
as my string is showing these as unicode

<font color='#0000FF'>'II &apos; II &quot; II &amp; ||'</font>

RTLabel showing it as it is '&apos; II &quot; II &amp; ||' and my expectation is 'II ' II " II & ||'

frame and height issue

Hi

there is issue in the RTLabel with its frame.
its height is not correct. Always shown only one line of text.

Screen Shot 2013-02-05 at 12 59 45 PM

Log

updateContentLabel.frame : {{0, 0}, {300, 100}}
optimumSize of RTLabel : {296.856, 82}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self rowHeightForRecord:nil];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float cellWidth = self.tableView.frame.size.width;

// other controls
    RTLabel *updateContentLabel;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DataCell"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DataCell"] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

// other controls

        updateContentLabel = [[RTLabel alloc] init];
        updateContentLabel.tag = 1006;
        updateContentLabel.backgroundColor = [UIColor redColor];
        updateContentLabel.lineBreakMode = RTTextLineBreakModeWordWrapping;
        updateContentLabel.lineSpacing = 20;
        [cell.contentView addSubview:updateContentLabel];

    } else {
// other controls
        updateContentLabel = (RTLabel *)[cell viewWithTag:1006];
    }

    id record = [activityUpdateArray objectAtIndex:indexPath.row];

    triggeredByAvtar.frame = CGRectMake(10, 10, 25, 25);
    triggeredByAvtar.image = [[StarshipImagesServices shared] getImageWithUrl:[record objectForKey:@"TriggeredByProfileImage"]];
    if ( triggeredByAvtar.image == nil ) {
        triggeredByAvtar.image = [UIImage imageNamed:@"img-fetching.png"];
    }

// other controls

    updateContentLabel.frame = CGRectMake(10, 35, cellWidth-20, 300);
    [self setUpdateContent:updateContentLabel forRecord:record];
    CGSize optimumSize = [updateContentLabel optimumSize];
    updateContentLabel.frame = CGRectMake(0, 0, cellWidth-20, 100); // set height 100 for temporary test

// other controls

    return cell;
}

-(void)setUpdateContent:(RTLabel *)contentLabel forRecord:(id)record {

    NSString *string1 = @"this is blue text this is blue text this is blue text this is blue text this is blue text this is blue text this is blue text this is blue text";
    NSString *string2 = @" black black black black black black ";
    NSString *string3 = @"this is blue text this is blue text this is blue text this is blue text this is blue text";
![Screen Shot 2013-02-05 at 12 59 45 PM](https://f.cloud.github.com/assets/641959/126586/fe601028-6f65-11e2-8503-80343a40c282.png)
    NSString *text = [NSString stringWithFormat:@"<font face='%@' size=12 color='#2E4AF7'>'%@'</font><font face='%@' size=12 color='#000000'> %@ </font><font face='%@' size=12 color='#2E4AF7'>%@</font>", FontRegular, string1, FontRegular, string2, FontRegular, string3];
    contentLabel.text = text;
    [contentLabel setParagraphReplacement:@""];
} 

-(float)rowHeightForRecord:(id)record {
    float cellWidth = self.tableView.frame.size.width;
    NSString *string1 = @"this is blue text this is blue text this is blue text this is blue text this is blue text this is blue text this is blue text this is blue text";
    NSString *string2 = @" black black black black black black ";
    NSString *string3 = @"this is blue text this is blue text this is blue text this is blue text this is blue text";
    NSString *text = [NSString stringWithFormat:@"<font face='%@' size=12 color='#2E4AF7'>'%@'</font><font face='%@' size=12 color='#000000'> %@ </font><font face='%@' size=12 color='#2E4AF7'>%@</font>", FontRegular, string1, FontRegular, string2, FontRegular, string3];
// FontRegular font defined globally, Optima in this case

    RTLabel *rtLabel = [[RTLabel alloc] initWithFrame:CGRectMake(0, 0, cellWidth-20, 300)];
    rtLabel.lineSpacing = 20.0;
    [rtLabel setText:text];
    CGSize optimumSize = [rtLabel optimumSize];
    NSLog(@" / / / /%@/ / / / ", NSStringFromCGSize(optimumSize));
    return optimumSize.height+60;
}

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.