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.
Related
As question title, I want to truncate a part of NSAttriutedString.
Here's my code.
UIButton *btnWelcome = [UIButton buttonWithType:UIButtonTypeCustom];
[btnWelcome setContentMode:UIViewContentModeCenter];
[btnWelcome.titleLabel setNumberOfLines:1];
NSMutableParagraphStyle *titleTextParagrahStyle = [[NSMutableParagraphStyle alloc] init];
NSMutableParagraphStyle *specificNameParagrahStyle = [[NSMutableParagraphStyle alloc] init];
[titleTextParagrahStyle setAlignment:NSTextAlignmentCenter];
[specificNameParagrahStyle setAlignment:NSTextAlignmentCenter];
[specificNameParagrahStyle setLineBreakMode:NSLineBreakByTruncatingTail];
NSDictionary *titleTextAttributes = #{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont boldSystemFontOfSize:17.0f], NSParagraphStyleAttributeName:titleTextParagrahStyle};
NSDictionary *specificNameAttributes = #{NSForegroundColorAttributeName:[UIColor blueColor], NSFontAttributeName:[UIFont boldSystemFontOfSize:17.0f], NSParagraphStyleAttributeName:specificNameParagrahStyle};
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#("Welcome To '%#' World!, 'VeryVeryLongSpeicificName'] attributes:titleTextAttributes];
NSRange specificNameRange = [attrString.string rangeOfString:[NSString stringWithFormat:#"'%#'", #"VeryVeryLongSpecificName"]];
specificNameRange.location++;
specificNameRange.length -= 2;
[attrString setAttributes:specificNameAttributes range:specificNameRange];
[btnWelcome setAttributedTitle:attrString forState:UIControlStateNormal];
The btnWelcome width is set to width of UIViewController.view
The Color Attribute of specificName is very well done.
But, setLineBreakMode:NSLineBreakByTruncatingTail doesn't apply.
Just shows below.
Welcome To 'VeryVeryLongSpec
The contents is just clipped.
The expectation result is below.
Welcome To 'VeryVeryLong...' World!
How to remove empty white space before and after some images that are small.
Some images are working well as the example below and some are with huge space above and below the image.
Am using Parse so I think I can't access imageView directly :
// upload Image To Parse as PFImageView
let imgFile = object?.objectForKey("ImgView") as? PFFile
cell.ImgView.file = imgFile
cell.questionImgView.loadInBackground()
// cell.questionImgView.clipsToBounds = true
cell. cell.ImgView.clipsToBounds.contentMode = UIViewContentMode.ScaleAspectFit
You can simply do the following to your UIButton to give it multiple lines and different fonts:
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setAlignment:NSTextAlignmentCenter];
[style setLineBreakMode:NSLineBreakByWordWrapping];
UIFont *font1 = [UIFont fontWithName:#"HelveticaNeue-Medium" size:20.0f];
UIFont *font2 = [UIFont fontWithName:#"HelveticaNeue-Light" size:20.0f];
NSDictionary *dict1 = #{NSUnderlineStyleAttributeName:#(NSUnderlineStyleSingle),
NSFontAttributeName:font1};
NSDictionary *dict2 = #{NSUnderlineStyleAttributeName:#(NSUnderlineStyleNone),
NSFontAttributeName:font2};
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] init];
[attString appendAttributedString:[[NSAttributedString alloc] initWithString:#"LINE 1\n" attributes:dict1]];
[attString appendAttributedString:[[NSAttributedString alloc] initWithString:#"line 2" attributes:dict2]];
[[self buttonToStyle] setAttributedTitle:attString forState:UIControlStateNormal];
[[[self buttonToStyle] titleLabel] setNumberOfLines:0];
[[[self buttonToStyle] titleLabel] setLineBreakMode:NSLineBreakByWordWrapping];
Source: iOS NSAttributedString on UIButton
I am trying to create a UILabel where some of the text is aligned to the right and some of the text is aligned to the left. It is similar to the UITableViewCell with the small arrow:
I am trying to do it with NSAttributedString , but can't figure out what is the correct way to tackle this.
Here is some code which isn't working. It is aligned to the right.
NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:#"Label >"];
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.alignment = NSTextAlignmentLeft;
[att addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, #"Label".length)];
NSMutableParagraphStyle *rightParagraph = [[NSMutableParagraphStyle alloc] init];
paragraph.alignment = NSTextAlignmentRight;
[att addAttribute:NSParagraphStyleAttributeName value:rightParagraph range:NSMakeRange(5, 1)];
You can use NSAttributedString to achieve your requirements, but it will be much better and cleaner approach to use two UILabels instead.
Use 2 labels.Assign the needed TextAlignment property to them. And after setting label text value, write this line :
[textLabel sizeToFit];
Though sizes of the labels varies it will set to minimum size. and will avoid text overlap.
I did it before with that code, Hope it also working for you.
NSString* alphaString = #“some text”;
NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = NSTextAlignmentLeft;
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc]
initWithString:alphaString
attributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"HelveticaNeue" size:13], NSFontAttributeName,
paragraphStyle, NSParagraphStyleAttributeName, nil]];
NSString * betaString = #“some other text”;
NSMutableParagraphStyle* paragraphStyle2 = [[NSMutableParagraphStyle alloc] init];
paragraphStyle2.alignment = NSTextAlignmentRight;
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:betaString attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:#"HelveticaNeue" size:13], NSFontAttributeName, paragraphStyle2, NSParagraphStyleAttributeName, nil]]];
yourLabel.attributedText = attributedString;
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
Can I set the attributedText property of a UILabel object? I tried the below code:
UILabel *label = [[UILabel alloc] init];
label.attributedText = #"asdf";
But it gives this error:
Property "attributedText" not found on object of type 'UILabel *'
#import <CoreText/CoreText.h> not working
Here is a complete example of how to use an attributed text on a label:
NSString *redText = #"red text";
NSString *greenText = #"green text";
NSString *purpleBoldText = #"purple bold text";
NSString *text = [NSString stringWithFormat:#"Here are %#, %# and %#",
redText,
greenText,
purpleBoldText];
// If attributed text is supported (iOS6+)
if ([self.label respondsToSelector:#selector(setAttributedText:)]) {
// Define general attributes for the entire text
NSDictionary *attribs = #{
NSForegroundColorAttributeName: self.label.textColor,
NSFontAttributeName: self.label.font
};
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:text
attributes:attribs];
// Red text attributes
UIColor *redColor = [UIColor redColor];
NSRange redTextRange = [text rangeOfString:redText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:#{NSForegroundColorAttributeName:redColor}
range:redTextRange];
// Green text attributes
UIColor *greenColor = [UIColor greenColor];
NSRange greenTextRange = [text rangeOfString:greenText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:#{NSForegroundColorAttributeName:greenColor}
range:greenTextRange];
// Purple and bold text attributes
UIColor *purpleColor = [UIColor purpleColor];
UIFont *boldFont = [UIFont boldSystemFontOfSize:self.label.font.pointSize];
NSRange purpleBoldTextRange = [text rangeOfString:purpleBoldText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:#{NSForegroundColorAttributeName:purpleColor,
NSFontAttributeName:boldFont}
range:purpleBoldTextRange];
self.label.attributedText = attributedText;
}
// If attributed text is NOT supported (iOS5-)
else {
self.label.text = text;
}
Unfortunately, UILabel doesn't support attributed strings. You can use OHAttributedLabel instead.
Update: Since iOS6, UILabel does support attributed strings. See UILabel reference or Michael Kessler's answer below for more details.
NSString *str1 = #"Hi Hello, this is plain text in red";
NSString *cardName = #"This is bold text in blue";
NSString *text = [NSString stringWithFormat:#"%#\n%#",str1,cardName];
// Define general attributes for the entire text
NSDictionary *attribs = #{
NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:12]
};
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attribs];
UIFont *boldFont = [UIFont fontWithName:#"Helvetica-Bold" size:14.0];
NSRange range = [text rangeOfString:cardName];
[attributedText setAttributes:#{NSForegroundColorAttributeName: [UIColor blueColor],
NSFontAttributeName:boldFont} range:range];
myLabel = [[UILabel alloc] initWithFrame:CGRectZero];
myLabel.attributedText = attributedText;
for Swift 4:
iOS 11 and xcode 9.4
let str = "This is a string which will shortly be modified into AtrributedString"
var attStr = NSMutableAttributedString.init(string: str)
attStr.addAttribute(.font,
value: UIFont.init(name: "AppleSDGothicNeo-Bold", size: 15) ?? "font not found",
range: NSRange.init(location: 0, length: str.count))
self.textLabel.attributedText = attStr
For people using swift, here's a one-liner:
myLabel.attributedText = NSMutableAttributedString(string: myLabel.text!, attributes: [NSFontAttributeName:UIFont(name: "YourFont", size: 12), NSForegroundColorAttributeName: UIColor.whiteColor()])
so,here is the code to have different properties for sub strings ,of a string.
NSString *str=#"10 people likes this";
NSString *str2=#"likes this";
if ([str hasSuffix:str2])
{
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:str];
// for string 1 //
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,str.length-str2.length)];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:NSMakeRange(0,str.length-str2.length)];
// for string 2 //
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange((str.length-str2.length),str2.length)];
[string addAttribute:NSFontAttributeName value:[UIFont italicSystemFontOfSize:12] range:NSMakeRange((str.length-str2.length),str2.length)];
label.attributedText=string;
}
else
{
label.text =str;
}
Hope this helps ;)
NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:#"asdf"];
[attrStr setFont:[UIFont systemFontOfSize:12]];
[attrStr setTextColor:[UIColor grayColor]];
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
lbl.attributedText = attrStr;
UIFont *font = [UIFont boldSystemFontOfSize:12];
NSDictionary *fontDict = [NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:#" v 1.2.55" attributes: fontDict];
UIFont *fontNew = [UIFont boldSystemFontOfSize:17];
NSDictionary *fontDictNew = [NSDictionary dictionaryWithObject: fontNew forKey:NSFontAttributeName];
NSMutableAttributedString *attrStringNew = [[NSMutableAttributedString alloc] initWithString:#“Application” attributes: fontDictNew];
[attrStringNew appendAttributedString: attrString];
self.vsersionLabel.attributedText = attrStringNew;