I need to display a string which will change every second.
For example :
View will refresh in 10 sec
View will refresh in 09 sec
View will refresh in 08 sec
View will refresh in 07 sec
..
View will refresh in 0 sec
The above string needs to be displayed with multiple properties of text, like-
1) The color of text - 'View will refresh in _ sec' will be White
2) The color of number - '10' , '09' ... will be Yellow.
As displayed in reference below :
How can I achieve this using only one label?
Many thanks in advance.
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] init];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:#"Will change in " attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:17], NSForegroundColorAttributeName : [UIColor whiteColor] }]];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:#"10 sec" attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:19], NSForegroundColorAttributeName : [UIColor yellowColor] }]];
myLabel.attributedText = str;
You can use string attributes like this (DOC):
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:yourString];
[attr addAttribute: NSForegroundColorAttributeName value: [UIColor blackColor] range: NSMakeRange(0, 4)]; // color for char 0 to 4
[attr addAttribute: NSForegroundColorAttributeName value: [UIColor blueColor] range: NSMakeRange(4, 8)]; // color for char 4 to 8
[myLabel setAttributedText: attr];
Then to include variables in your NSString, you can use :
[NSString stringWithFormat:#"Hello %# !", myVariable]; // %# will be replace by myVariable
Try this
- (void)viewDidLoad
{
[super viewDidLoad];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateLabelText:) userInfo:nil repeats:YES];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] init];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:#"Will change in " attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:17], NSForegroundColorAttributeName : [UIColor whiteColor] }]];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:#"10 Sec" attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:19], NSForegroundColorAttributeName : [UIColor yellowColor] }]];
myLabel.attributedText = str;
}
- (NSString *)extractNumberFromText:(NSString *)text
{
NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
return [[text componentsSeparatedByCharactersInSet:nonDigitCharacterSet] componentsJoinedByString:#""];
}
-(void)updateLabelText:(NSTimer *) timerLocal
{
int labelCount = [[self extractNumberFromText:myLabel.text]intValue];
if (labelCount!=0)
{
labelCount--;
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] init];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:#"Will change in " attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:17], NSForegroundColorAttributeName : [UIColor whiteColor] }]];
[str appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#"%i Sec",labelCount] attributes:#{ NSFontAttributeName : [UIFont systemFontOfSize:19], NSForegroundColorAttributeName : [UIColor yellowColor] }]];
myLabel.attributedText = str;
}
else
{
[timerLocal invalidate];
}
}
create a label in storyboard set the constraint such that it can accommodate variable width
name the label as myLabel ;
here is .m file
//
// ViewController.m
// TimerLogic
//
//
#import "ViewController.h"
#interface ViewController ()
{
NSInteger currentTime ;
NSTimer *myTimer ;
}
#end
#implementation ViewController
#synthesize myLabel ;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
currentTime = 10 ;
[self.view addSubview:myLabel];
myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(createLabel:) userInfo:nil repeats:YES] ;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)createLabel:(NSTimer *)theTimer
{
if(currentTime == 10)
{
myLabel.backgroundColor = [UIColor redColor] ;
myLabel.text = #"Thats me" ;
myLabel.textColor = [UIColor yellowColor];
myLabel.translatesAutoresizingMaskIntoConstraints = NO ;
// NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"V: | -offsetTop-[label]" options:0 metrics:#{#"offsetTop":#100 } views:NSDictionaryOfVariableBindings(myLabel)];
}
if(currentTime == 9)
{
myLabel.backgroundColor = [UIColor greenColor] ;
myLabel.text = #"Thats me again 1" ;
myLabel.textColor = [UIColor whiteColor];
}
if (currentTime == 8)
{
myLabel.backgroundColor = [UIColor greenColor] ;
myLabel.text = #"Thats me again 2" ;
myLabel.textColor = [UIColor blackColor];
}
// like that for all values
if(currentTime == 7)
{
myLabel.backgroundColor = [UIColor purpleColor] ;
myLabel.text = #"Thats me again 3" ;
[myTimer invalidate ] ;
myLabel.textColor = [UIColor yellowColor];
}
currentTime-- ;
}
#end
If it is in webview than we can use CSS but it's UILabel so u can use below links for UILabels:-
1) https://github.com/AliSoftware/OHAttributedLabel/
2) https://github.com/mattt/TTTAttributedLabel/
3) https://github.com/joaoffcosta/UILabel-FormattedText
Hope this'll work for u.
Related
I'm trying to set the font of UITextField programatically. The issue is that it works in a strange manner.
I have multiple UITextFields in a UITableViewController.
I tried setting the font this way
[self.textfieldProspect setFont:nil];
[self.textfieldProspect setFont:[UIFont systemFontOfSize:15]];
I put the above code in ViewDidLoad, ViewWillAppear and ViewDidLayoutSubviews.
It only works in ViewDidLayoutSubviews. Which causes the textField to change it's font visibly once the view controller becomes visible. I do not want that, I would like the font to be set before the ViewController becomes visible.
I present the viewController modally.
Is there anyway to change font before the textField becomes visible. It sounds like a trivial question, but I tried everything and nothing seems to work.
Here is the complete code
#import <UIKit/UIKit.h>
#protocol AddActivityViewControllerDelegate;
#interface AddActivityViewController : UITableViewController
#end
- (void)viewDidLoad
{
[super viewDidLoad];
self.themeManager = [ThemeManager sharedThemeManager];
[self.themeManager applyAppBackgroundColorToView:self.view];
self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
self.textviewNotes.text = #"";
self.textviewNotes.placeholder = #"Notes";
self.textviewNotes.placeholderColor = [CommonHelper getSelectedVarientPlaceHolderColor];
[self setUpTextFieldsPaddingView];
self.dateFormatter = [CommonHelper getDateFormatterWithFormat:#"MMM d, yyyy h:mm a"];
UIToolbar *toolbar = [[UIToolbar alloc] init];
[toolbar setBarStyle:UIBarStyleBlackTranslucent];
[toolbar sizeToFit];
UIBarButtonItem* doneButton =[[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:self action:#selector(resignKeyboardCustom:)];
NSArray *itemsArray = [NSArray arrayWithObjects:doneButton,nil];
[toolbar setItems:itemsArray animated:NO];
[self.fieldEndDate setInputAccessoryView:toolbar];
[self.fieldStartDate setInputAccessoryView:toolbar];
self.datePicker = [[UIDatePicker alloc] init];
self.datePicker.datePickerMode = UIDatePickerModeDateAndTime;
//self.datePicker.minimumDate = [NSDate date];
[self.datePicker addTarget:self action:#selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
self.fieldStartDate.inputView = self.datePicker;
self.fieldEndDate.inputView = self.datePicker;
UIView* seperatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, self.navigationController.navigationBar.frame.size.width, 1)];
seperatorView.backgroundColor = [UIColor lightGrayColor];
[self.navigationController.navigationBar addSubview:seperatorView];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,64,30);
[btn setBackgroundColor:[UIColor darkGrayColor]];
[btn setTitle:#"Cancel" forState:UIControlStateNormal];
btn.titleLabel.font = [self.themeManager getSelectedFont];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(hideViewController) forControlEvents:UIControlEventTouchUpInside];
btn.layer.cornerRadius = 3.0f;
UIBarButtonItem *barBackBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,64,30);
[btn setBackgroundColor:[UIColor darkGrayColor]];
[btn setTitle:#"Done" forState:UIControlStateNormal];
btn.titleLabel.font = [self.themeManager getSelectedFont];
[btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(doneButtonTapped) forControlEvents:UIControlEventTouchUpInside];
btn.layer.cornerRadius = 3.0f;
UIBarButtonItem *barDoneBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.rightBarButtonItem = barDoneBtn;
self.navigationItem.leftBarButtonItem = barBackBtn;
//Data Models
///////////////////////////////////////////////////////////////////
Up_DateAppDelegate* appDelegate = (Up_DateAppDelegate*)[UIApplication sharedApplication].delegate;
self.managedObjectContext = appDelegate.managedObjectContext;
self.prospect = [appDelegate GetSelectedProspect];
NSLog(#"nickname%#",self.prospect.nickName);
NSLog(#"firstname%# ",self.prospect.firstName);
NSLog(#"lastname %#",self.prospect.lastName);
self.btnDeleteActivity.hidden = YES;
self.selectedStartDate = [NSDate date];
isStartDateSelected = YES;
self.fieldStartDate.text = [self.dateFormatter stringFromDate:self.selectedStartDate];
if (self.isCalendarMode == YES)
{
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults synchronize];
NSDate* startDate = [userDefaults objectForKey:#"CurrentSelectedMonthForCalendar"];
//Getting current time
NSDate* currentTime = [NSDate date];
NSCalendar* theCalendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponent = [theCalendar components:( NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ) fromDate:startDate];
//[dayComponent setTimeZone:[NSTimeZone defaultTimeZone]];
NSDateComponents* timeComponents = [theCalendar components:(NSCalendarUnitHour) fromDate:currentTime];
[dayComponent setHour:timeComponents.hour];
[dayComponent setMinute:0];
[dayComponent setSecond:0];
startDate = [theCalendar dateFromComponents:dayComponent];
self.initiallySelectedDateForCalendarMode = startDate;
self.selectedStartDate = startDate;
self.fieldStartDate.text = [self.dateFormatter stringFromDate:startDate];
//Autocomplete Search options for prospects
activityProspectsAutocompleteVC = [ActivityProspectsAutocompleteViewController createAndSetupAutoCompleteWithDisplayViewController:self textfield:self.textfieldProspect];
[self.view addSubview:tableviewAutoCompleteProspects];
}
self.fieldEndDate.text = #"";
self.resultLevelSelected = #"None";
self.repeatCountSelected = 0;
self.repeatOptionSelected = #"Never";
self.alertOptionSelected = #"None";
[self.timeInvestmentLabel setFont:[UIFont fontWithName:[CommonHelper getBoldFontForFontName:[self.themeManager getSelectedFontName]] size:[self.themeManager getBiggerFontSize]]];
[self.timeInvestmentLabel setTextColor:[UIColor whiteColor]];
[self.resultLabel setFont:[UIFont fontWithName:[CommonHelper getBoldFontForFontName:[self.themeManager getSelectedFontName]] size:[self.themeManager getBiggerFontSize]]];
[self.resultLabel setTextColor:[UIColor whiteColor]];
self.timeInvestmentLabel.attributedText = [[NSAttributedString alloc] initWithString:#"Time Investment" attributes:#{ NSStrokeColorAttributeName : [UIColor blackColor], NSForegroundColorAttributeName : [UIColor whiteColor], NSStrokeWidthAttributeName : #-3.5}];
self.resultLabel.attributedText = [[NSAttributedString alloc] initWithString:#"Result?" attributes:#{ NSStrokeColorAttributeName : [UIColor blackColor], NSForegroundColorAttributeName : [UIColor whiteColor], NSStrokeWidthAttributeName : #-3.5}];
NSAttributedString *attributedText =
[[NSAttributedString alloc] initWithString:#" Result"
attributes:#{NSStrokeWidthAttributeName: [NSNumber numberWithInt:-3],
NSStrokeColorAttributeName: [UIColor lightGrayColor],
NSForegroundColorAttributeName: [UIColor whiteColor]}];
[self.btnResultLevel setAttributedTitle:attributedText forState:UIControlStateNormal];
if (self.isCalendarMode == NO)
{
//coming from prospect
self.textfieldProspect.userInteractionEnabled = NO;
}
NSString* pageTitle = #"";
if (self.editModeEnabled == NO)
{
//Add Activity for a Pospect
self.textfieldProspect.text = [CommonHelper getDisplayNameForProspec:self.prospect];
[self.textfieldProspect setFont:nil];
[self.textfieldProspect setFont:[self.themeManager getSelectedBiggerFont]];
if (self.isCalendarMode == YES)
{
self.textfieldProspect.text = #"";
[self.textfieldProspect setFont:nil];
[self.textfieldProspect setFont:[self.themeManager getSelectedBiggerFont]];
}
pageTitle = #"Add Activity";
}
else
{
//Edit Mode
[self setUpFieldsValuesFromDataModel];
pageTitle = #"Edit Activity";
}
// Creating custom title view so that we can apply font of our choice
CGRect frame = CGRectMake(0, 0, 200, 21);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont fontWithName:[CommonHelper getBoldFontForFontName:[self.themeManager getSelectedFontName]] size:[self.themeManager getBiggerFontSize]];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.text = pageTitle;
self.navigationItem.titleView = label;
//Delete Activity button
[self.btnDeleteActivity.layer setShadowColor:[UIColor blackColor].CGColor];
[self.btnDeleteActivity.layer setShadowOpacity:1.0];
[self.btnDeleteActivity.layer setShadowRadius:3.0];
[self.btnDeleteActivity.layer setShadowOffset:CGSizeMake(0,3.0)];
self.btnDeleteActivity.layer.masksToBounds = NO;
self.btnDeleteActivity.layer.cornerRadius = 3.0f;
}
-(void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
[self.textfieldProspect setFont:nil];
[self.textfieldProspect setFont:[self.themeManager getSelectedBiggerFont]];
[self.textfieldActivity setFont:nil];
[self.textfieldActivity setFont:[self.themeManager getSelectedBiggerFont]];
[self.textfieldLocation setFont:nil];
[self.textfieldLocation setFont:[self.themeManager getSelectedBiggerFont]];
[self.textfieldWebsite setFont:nil];
[self.textfieldWebsite setFont:[self.themeManager getSelectedBiggerFont]];
[self.fieldEndDate setFont:nil];
[self.fieldEndDate setFont:[self.themeManager getSelectedBiggerFont]];
[self.fieldStartDate setFont:nil];
[self.fieldStartDate setFont:[self.themeManager getSelectedBiggerFont]];
[self.textfieldMonetaryInvestment setFont:nil];
[self.textfieldMonetaryInvestment setFont:[self.themeManager getSelectedBiggerFont]];
}
hi i want a textview or label with see more and less functionality. i tried with label and successfully got result as:
but if text will increase it button more will look like :
and in some conditions it will look :
i am trying to set button will automatically set according to text.can anyone suggest me better way to got this.
If you are using UILabel than you can use TTTAttributedLabel in that you can set clickable text.
Append your string "see more" or "less functionality" with label text and make it clickable.
So there is my simple code that create label with TTTAttributedLabel to implement 'more...' and 'less...' functionality for label:
- (void) setupStoreTitleLabel {
self.titleLabel.delegate = self;
[self.titleLabel setText:self.card.name];
self.titleLabel.numberOfLines = 2;
NSAttributedString *showMore = [[NSAttributedString alloc] initWithString:#" more..." attributes:#{
NSForegroundColorAttributeName:[UIColor blueColor],
NSFontAttributeName : [UIFont boldSystemFontOfSize:12],
NSLinkAttributeName : [NSURL URLWithString:#"more..."]
}];
[self.titleLabel setAttributedTruncationToken:showMore];
}
#pragma mark - TTTAttributedLabelDelegate
- (void)attributedLabel:(__unused TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url
{
NSLog(#"%# pressed", url);
if ([[url absoluteString] isEqualToString:#"more..."]) {
self.titleLabel.numberOfLines = 99;
NSString *cardNameWithLess = [NSString stringWithFormat:#"%# %#",self.card.name, #" less..."];
[self.titleLabel setText:cardNameWithLess afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
//code
NSRange linkRange = [[mutableAttributedString string] rangeOfString:#" less..." options:NSCaseInsensitiveSearch];
[mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:linkRange];
[mutableAttributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:linkRange];
[mutableAttributedString addAttribute:NSLinkAttributeName value:[NSURL URLWithString:#"less..."] range:linkRange];
return mutableAttributedString;
}];
} else {
self.titleLabel.numberOfLines = 2;
NSAttributedString *showMore = [[NSAttributedString alloc] initWithString:#" more..." attributes:#{
NSForegroundColorAttributeName:[UIColor blueColor],
NSFontAttributeName : [UIFont boldSystemFontOfSize:12],
NSLinkAttributeName : [NSURL URLWithString:#"more..."]
}];
[self.titleLabel setAttributedTruncationToken:showMore];
[self.titleLabel setText:self.card.name];
}
}
I have a UITextView with multiple URLs that I activate by setting the dataDetectorTypes property to UIDataDetectorTypeLink. I then use the linkTextAttributes property to set the color of the links. Now when the user taps on one of the links (using a UITapGestureRecognizer), I'd like to change the color of that link only. If I change linkTextAttributes, all the links will change color.
How can I change just the color of the link that was tapped on?
If these urls are fixed.
For example:
I have the following urls:
http://www.123.com
http://www.456.com
http://www.789.com
I would put them to an NSAttributedString
Use NSMutableAttributedString to combine them all
NSMutableAttributedString *urlsAttributedText = [[NSMutableAttributedString alloc]init];
NSAttributedString *url1 = [[NSAttributedString alloc]initWithString:NSLocalizedString(#"http://www.123.com\n", nil) attributes:#{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : [UIFont systemFontOfSize:15.0f]}];
NSAttributedString *url2 = [[NSAttributedString alloc]initWithString:NSLocalizedString(#"http://www.456.com\n", nil) attributes:#{NSForegroundColorAttributeName : [UIColor greenColor], NSFontAttributeName : [UIFont systemFontOfSize:15.0f]}];
NSAttributedString *url3 = [[NSAttributedString alloc]initWithString:NSLocalizedString(#"http://www.789.com\n", nil) attributes:#{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : [UIFont systemFontOfSize:15.0f]}];
[urlsAttributedText url1];
[urlsAttributedText appendAttributedString:url2];
[urlsAttributedText appendAttributedString:url3];
self.texView.attributedText = urlsAttributedText;
Cheers!
I think I solved it, using a subclass of UITextView called which has a rangeOfLink property.
First, in my UIViewController viewDidLoad:, I add
self.textView.dataDetectorTypes = UIDataDetectorTypeLink; // change for other link types
self.textView.selectable = YES;
self.textView.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget: self action: #selector(handleTap:)];
tapGesture.cancelsTouchesInView = YES;
[self.textView addGestureRecognizer: tapGesture];
[self.textView setNeedsDisplay]; // force a redraw so that drawRect is called
Then in handleTap, I do this:
MyTextViewWithLink *aTextView = (IDTextViewWithLink *) recognizer.view;
if (aTextView != self.textView)
return;
if (recognizer.state == UIGestureRecognizerStateEnded)
{
CGPoint location = [recognizer locationInView: aTextView];
// this returns an NSTextCheckingResult if location is inside a link
NSTextCheckingResult *result = [self textCheckingResultAtPoint: location inTextView: aTextView];
if (result)
{
aTextView.rangeOfLink = result.range;
[aTextView setNeedsDisplay]; // this will force the color change
// open url
}
}
Finally I override drawRect in my UITextView subclass:
self.linkTextAttributes = [NSDictionary dictionary];
NSError *error = nil;
NSDataDetector *dataDetector = [NSDataDetector dataDetectorWithTypes: NSTextCheckingTypeLink error: &error]; // change for other link types
if (!error && dataDetector)
{
NSArray* resultString = [dataDetector matchesInString: self.text
options: NSMatchingReportProgress
range: NSMakeRange(0, [self.text length])];
if (resultString.count > 0)
{
NSMutableAttributedString *mas = [self.attributedText mutableCopy];
for (NSTextCheckingResult* result in resultString)
{
if (result.resultType == NSTextCheckingTypeLink)
{
NSRange intersection = NSIntersectionRange(result.range, self.rangeOfLink);
if (intersection.length <= 0) // no match
[mas addAttribute: NSForegroundColorAttributeName
value: [UIColor blueColor]
range: self.rangeOfLink];
else
[mas addAttribute: NSForegroundColorAttributeName
value: [UIColor redColor]
range: self.rangeOfLink];
}
}
self.attributedText = mas;
}
}
[super drawRect: rect];
Now if the textView has more than one link, only the selected one will change color.
I have a UILabel acting like a ticker so every 0.09 seconds the text is being changed, but when a space comes at the end of the label it is being trimmed, so it is looking like the ticker is lagging.
Here’s the code:
[self setTickerLabel: [ [UILabel alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 40, self.view.bounds.size.width, 40)]];
[self.tickerLabel setFont:[UIFont fontWithName:#"Courier" size:TICKER_FONT_SIZE]];
self.text =[NSString stringWithFormat:#"%#",self.result];
self.tickerLabel.textAlignment = NSTextAlignmentRight;
[self.tickerLabel setText:self.text];
[self.tickerLabel setLineBreakMode:NSLineBreakByWordWrapping];
[NSTimer scheduledTimerWithTimeInterval:TICKER_RATE target:self selector: #selector(nudgeTicker:) userInfo:nil repeats:YES];
[self.view addSubview:self.tickerLabel];
The nudge Ticker method does the following:
NSString* firstLetter = [self.text substringWithRange: NSMakeRange(0,1)];
NSString* remainder = [self.text substringWithRange:NSMakeRange(1,[self.text length]-1)];
self.text=[remainder stringByAppendingString: firstLetter];
self.tickerLabel.text=self.text;
I really need some help. How can I fix this? By the way the text of the UILabel is in Arabic.
A bit of a hack, but one solution would be to use an attributed string in your label and include a transparent period (".") at the end of the string.
Just replace your nudgeTicker: method.
- (void)nudgeTicker:(id)target {
NSString* firstLetter = [self.text substringWithRange: NSMakeRange(0,1)];
NSString* remainder = [self.text substringWithRange:NSMakeRange(1,[self.text length]-1)];
self.text=[remainder stringByAppendingString: firstLetter];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#.", self.text]];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,string.length-1)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor clearColor] range:NSMakeRange(string.length-1,1)];
self.tickerLabel.attributedText = string;
}
I am using this code to change color of label and set text as strike through:
sliderlabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(10, 260, 310, 30)];
sliderlabel.font = [UIFont fontWithName:#"Optima-Bold" size:14];
[sliderlabel setTag:112];
sliderlabel.lineBreakMode = UILineBreakModeWordWrap;
[sliderlabel setBackgroundColor:[UIColor clearColor]];
NSString *sliderlabeltext = [NSString stringWithFormat:#"Change To: In-Progress (%d %%)",(int)slider.value];
[sliderlabel setText:sliderlabeltext afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange boldRange = [[mutableAttributedString string] rangeOfString:[NSString stringWithFormat:#"In-Progress (%d %%)",(int)slider.value] options:NSCaseInsensitiveSearch];
NSRange strikeRange = [[mutableAttributedString string] rangeOfString:sliderlabeltext options:NSCaseInsensitiveSearch];
UIFont *boldSystemFont = [UIFont fontWithName:#"Optima-Bold" size:14];
CTFontRef font = CTFontCreateWithName((CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
if (font) {
[mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[UIColor colorWithRed:8/255.0 green:156/255.0 blue:94/255.0 alpha:1.0].CGColor range:boldRange];//34-139-34
[mutableAttributedString addAttribute:kTTTStrikeOutAttributeName value:[NSNumber numberWithBool:YES] range:strikeRange];
CFRelease(font);
}
return mutableAttributedString;
}];
[self.view addSubview:sliderlabel];
[sliderlabel release];
Now I want it to be without strike through when I perform some operation like click on a button, passing [NSNumber numberWithBool:NO] in addAttribute:value:range doesnt work. Any suggestions?
Try this additions.
#implementation TTTAttributedLabel (Additions)
- (void)setStrikeThroughOn:(BOOL)isStrikeThrough {
NSString* text = self.text;
[self setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange strikeRange = [[mutableAttributedString string] rangeOfString:text options:NSCaseInsensitiveSearch];
[mutableAttributedString addAttribute:kTTTStrikeOutAttributeName value:[NSNumber numberWithBool:isStrikeThrough] range:strikeRange];
return mutableAttributedString;
}];
// must trigger redraw
[self setNeedsDisplay];
}
#end