I'm attempting to change my UIBarButtonItem font. It looks good when ViewControllers load. But if I tap on the bar button, or swipe right as if to move to the previous ViewController (but then pull back to the current one), the font changes back to the system font. Here's what I'm setting in my AppDelegate:
NSDictionary* barButtonItemAttributes = #{NSFontAttributeName: [UIFont fontWithName:#"SourceSansPro-Light" size:20.0f]};
[[UIBarButtonItem appearance] setTitleTextAttributes: barButtonItemAttributes forState:UIControlStateNormal];
[[UIBarButtonItem appearance] setTitleTextAttributes: barButtonItemAttributes forState:UIControlStateHighlighted];
[[UIBarButtonItem appearance] setTitleTextAttributes: barButtonItemAttributes forState:UIControlStateSelected];
[[UIBarButtonItem appearance] setTitleTextAttributes: barButtonItemAttributes forState:UIControlStateDisabled];
And here's an example of my viewWillAppear:
- (void) viewWillAppear:(BOOL)animated {
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStylePlain target:self action:#selector(doneButtonPressed)];
self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:141.0/255.0 green:209.0/255.0 blue:205.0/255.0 alpha:1.0];
}
Am I somehow changing the font back, or am I misusing the appearance proxy?
The problem is that the tintColor setting conflicts with the title text attributes. Comment out that line and all will be well.
If you are going to use title text attributes, then incorporate the text color into those attributes:
NSDictionary* barButtonItemAttributes =
#{NSFontAttributeName:
[UIFont fontWithName:#"Georgia" size:20.0f],
NSForegroundColorAttributeName:
[UIColor colorWithRed:141.0/255.0 green:209.0/255.0 blue:205.0/255.0 alpha:1.0]
};
By using this approach in viewDidLoad method you can set custom text,font,size etc all at once place.
UIView *customBarButtonView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 30)];
UIButton *buttonDone = [UIButton buttonWithType:UIButtonTypeSystem];
[buttonDone addTarget:self action:#selector(doneButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
buttonDone.frame = CGRectMake(10, 0, 50, 30);
buttonDone.titleLabel.textColor = [UIColor colorWithRed:141.0/255.0 green:209.0/255.0 blue:205.0/255.0 alpha:1.0];
buttonDone.titleLabel.font = [UIFont fontWithName:#"SourceSansPro-Light" size:20.0f];
[buttonDone setTitle:#"Done" forState:UIControlStateNormal];
[customBarButtonView addSubview:buttonDone];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:customBarButtonView];
_myrButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"French KeyBoard" style:UIBarButtonItemStylePlain target:self action:#selector(RbuttonItemdown:)];
NSDictionary* itemTextAttributes = #{NSFontAttributeName:[UIFont fontWithName:#"Georgia" size:12.0f], NSForegroundColorAttributeName:[UIColor blueColor], NSBackgroundColorAttributeName:[UIColor lightGrayColor]};
[_myrButtonItem setTitleTextAttributes:itemTextAttributes forState:UIControlStateNormal];
[self.navigationItem setRightBarButtonItem:_myrButtonItem];
You can use all of this :
NSString *const NSFontAttributeName ;
NSString *const NSParagraphStyleAttributeName ;
NSString *const NSForegroundColorAttributeName ;
NSString *const NSBackgroundColorAttributeName ;
NSString *const NSLigatureAttributeName ;
NSString *const NSKernAttributeName ;
NSString *const NSStrikethroughStyleAttributeName ;
NSString *const NSUnderlineStyleAttributeName ;
NSString *const NSStrokeColorAttributeName ;
NSString *const NSStrokeWidthAttributeName ;
NSString *const NSShadowAttributeName ;
NSString *const NSTextEffectAttributeName ;
NSString *const NSAttachmentAttributeName ;
NSString *const NSLinkAttributeName ;
NSString *const NSBaselineOffsetAttributeName ;
NSString *const NSUnderlineColorAttributeName ;
NSString *const NSStrikethroughColorAttributeName ;
NSString *const NSObliquenessAttributeName ;
NSString *const NSExpansionAttributeName ;
NSString *const NSWritingDirectionAttributeName ;
NSString *const NSVerticalGlyphFormAttributeName;
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]];
}
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.
Is there any support for spannable string in iOS?
I would like to create an underlineSpan and on click of it and then open some other view controller.
NSAttributedString *title;
title = [[NSAttributedString alloc] initWithString:#"hello how r u..." attributes:#{ NSFontAttributeName : [UIFont fontWithName:#"Noteworthy-Bold" size:15], NSUnderlineStyleAttributeName : #1 , NSStrokeColorAttributeName : [UIColor blackColor]}]; //1
UILabel *label;
label = [[UILabel alloc] initWithFrame:CGRectMake( (self.view.bounds.size.width - title.size.width) / 2.0f, 40.0f, title.size.width, title.size.height)]; //2
label.attributedText = title; //3
[self.view addSubview:label];
Yes, they are called NSAttributedStrings in iOS.
Example Code to Add underline
NSString *str = #"Amit";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(0, 4)];
More info # Apple Documentation
To add link to that underline you check out this code:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:#"Google Webpage"];
[attributedString addAttribute:NSLinkAttributeName
value:#"http://www.google.com"
range:[[attributedString string] rangeOfString:#"Google Webpage"]];
NSDictionary *linkAttributes = #{NSForegroundColorAttributeName: [UIColor greenColor],
NSUnderlineColorAttributeName: [UIColor lightGrayColor],
NSUnderlineStyleAttributeName: #(NSUnderlinePatternSolid)};
// assume that textView is a UITextView previously created (either by code or Interface Builder)
textView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;
textView.delegate = self;
This source code was found # Raywenderlich website
I was trying to play a video in background in my app, but it didn't work when I was using Storyboard. I read something about ARC and tried everything, but my video won't simply play. I tried the exact same thing but with another project where I deleted the Storyboard-file, and there it worked. I need to use this in my project where I'm using Storyboard. Please help me.
Here's the code:
ViewController.m:
#import "AnimatedLoginViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <QuartzCore/QuartzCore.h>
#interface ViewController (){
MPMoviePlayerController *player;
}
#property (nonatomic, strong) MPMoviePlayerController *player;
#end
#implementation ViewController
#synthesize player;
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect screen = [[UIScreen mainScreen] bounds];
NSURL *movieUrl = [[NSBundle mainBundle] URLForResource:#"background" withExtension:#"mp4"];
self.player = [[MPMoviePlayerController alloc] initWithContentURL:movieUrl];
player.view.frame = screen;
player.scalingMode = MPMovieScalingModeFill;
[self.player setControlStyle:MPMovieControlStyleNone];
[self.view addSubview:player.view];
[player prepareToPlay];
UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake(65, 90, 190, 40)];
logo.backgroundColor = [UIColor clearColor];
[logo setImage:[UIImage imageNamed:#"logo_welcome.png"]];
[self.view addSubview:logo];
UIFont *boldFont = [UIFont fontWithName:#"HelveticaNeue-Bold" size:16.0];
UIFont *defaultFont = [UIFont fontWithName:#"HelveticaNeue" size:16.0];
NSDictionary * attributes = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor whiteColor], defaultFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
NSDictionary * attributesBold = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor whiteColor], boldFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
attributes = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor blackColor], defaultFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
attributesBold = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor blackColor], boldFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
UIButton *emailButton = [UIButton buttonWithType:UIButtonTypeCustom];
[emailButton setFrame:CGRectMake(10, screen.size.height==568?455:370, 300, 43)];
attributedString = [[NSMutableAttributedString alloc] init];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:#"Enter your work " attributes:attributes]];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:#"Email" attributes:attributesBold]];
[emailButton setAttributedTitle:attributedString forState:UIControlStateNormal];
[emailButton setBackgroundImage:[UIImage imageNamed:#"SignInMailButton.png"] forState:UIControlStateNormal];
[emailButton setBackgroundImage:[UIImage imageNamed:#"SignInMailButtonTap.png"] forState:UIControlStateHighlighted];
[emailButton setBackgroundImage:[UIImage imageNamed:#"SignInMailButtonTap.png"] forState:UIControlStateSelected];
[emailButton setEnabled:YES];
[self.view addSubview:emailButton];
boldFont = [UIFont fontWithName:#"HelveticaNeue-Bold" size:14.0];
defaultFont = [UIFont fontWithName:#"HelveticaNeue" size:14.0];
attributes = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor grayColor], defaultFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
attributesBold = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor whiteColor], boldFont, nil] forKeys:[NSArray arrayWithObjects:NSForegroundColorAttributeName, NSFontAttributeName, nil]];
UIButton *signInButton = [UIButton buttonWithType:UIButtonTypeCustom];
[signInButton setFrame:CGRectMake(10, screen.size.height==568?500:410, 300, 43)];
attributedString = [[NSMutableAttributedString alloc] init];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:#"Do you have an activation code? " attributes:attributes]];
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:#"Enter now" attributes:attributesBold]];
[signInButton setAttributedTitle:attributedString forState:UIControlStateNormal];
[signInButton setEnabled:YES];
[self.view addSubview:signInButton];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playVideo)
name:MPMoviePlayerReadyForDisplayDidChangeNotification
object:player];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayerDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.player];
[player play];
}
- (void)moviePlayerDidFinish:(NSNotification *)note
{
if (note.object == self.player) {
NSInteger reason = [[note.userInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] integerValue];
if (reason == MPMovieFinishReasonPlaybackEnded)
{
[self.player play];
}
}
}
-(void)playVideo{
[player play];
}
#end
I have builed a button with two titles line by this code:
rootBntUI.titleLabel.font = [UIFont fontWithName:#"Avenir-Black" size:UserListFontSize];
[rootBntUI.layer setBorderWidth:0];
rootBntUI.titleLabel.textColor = [UIColor whiteColor];
rootBntUI.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
rootBntUI.titleLabel.textAlignment = NSTextAlignmentCenter;
rootBntUI.titleLabel.numberOfLines = 2;
Everything is working fine but how can I control line spacing of button title?
You can do the styling from the xib . Use button title attributed in attribute inspector and you can set all the styling parameter along with spacing .
I have resolved my problem, and this solution for anyone who have similar question.
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setAlignment:NSTextAlignmentCenter];
[style setLineBreakMode:NSLineBreakByWordWrapping];
[style setLineSpacing:-50];
UIFont *font1 = [UIFont fontWithName:#"Avenir-Black" size:UserListFontSize];
NSDictionary *dict1 = #{NSUnderlineStyleAttributeName:#(NSUnderlineStyleSingle),
NSFontAttributeName:font1,
NSParagraphStyleAttributeName:style};
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] init];
[attString appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#", obj] attributes:dict1]];
[FriendBnt setAttributedTitle:attString forState:UIControlStateNormal];
[[FriendBnt titleLabel] setNumberOfLines:0];
[[FriendBnt titleLabel] setLineBreakMode:NSLineBreakByWordWrapping];
Happy coding.
This works in Swift 2 using .lineHeightMultiple to compress the title text on a button.
let style = NSMutableParagraphStyle()
style.lineHeightMultiple = 0.8
style.alignment = .Center
style.lineBreakMode = .ByWordWrapping
let dict1:[String:AnyObject] = [
NSParagraphStyleAttributeName: style,
NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue
]
let attrString = NSMutableAttributedString()
attrString.appendAttributedString(NSAttributedString(string: "Button Text here over two lines", attributes: dict1))
myButton.setAttributedTitle(attrString, forState: .Normal)
myButton.titleLabel?.numberOfLines = 0
What really worked for me to change line height of the UIButton title label, was this:
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.maximumLineHeight = 12.0;
style.minimumLineHeight = 12.0;
UIColor *colorO = [UIColor whiteColor];
UIColor *colorD = [UIColor redColor];
NSDictionary *firstAttributes = #{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:getFloatScaledFactor(13.0)],
NSForegroundColorAttributeName : colorO,
NSParagraphStyleAttributeName:style
};
NSDictionary *secondAttributes = #{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:getFloatScaledFactor(13.0)],
NSForegroundColorAttributeName : colorD,
NSParagraphStyleAttributeName:style
};
NSArray *textArray = [title componentsSeparatedByString:#"\n"];
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] init];
[attString appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#", textArray[0]] attributes:firstAttributes]];
[attString appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#"%#", textArray[1]] attributes:secondAttributes]];
[self.btnRight setAttributedTitle:attString forState:UIControlStateNormal];
As a alternative solution.