This question already has answers here:
How can I debug 'unrecognized selector sent to instance' error
(9 answers)
Closed 8 years ago.
I'm displaying an array of dictionaries that comes from web service, in a table. This is the code snippet in cellForRowAtIndexPath.
cell.businessNameLabel.text = [dataDict objectForKey:#"business_name"];
[cell.businessNameLabel setTextColor:[UIColor colorWithRed:1.0/255.0 green:135.0/255.0 blue:68.0/255.0 alpha:1]];
UIFont *customfont = [UIFont fontWithName:#"MyriadPro-Bold" size:16];
[cell.businessNameLabel setFont:customfont];
cell.serviceTypeLabel.text = [dataDict objectForKey:#"address"];
[cell.serviceTypeLabel setTextColor:[UIColor blackColor]];
customfont = [UIFont fontWithName:#"MyriadPro-Regular" size:11];
[cell.serviceTypeLabel setFont:customfont];
cell.businessID = [dataDict objectForKey:#"business_id"];
cell.reviewScoreLabel.text = [dataDict objectForKey:#"rating"];
return cell;
The app crashes on the following line:
cell.reviewScoreLabel.text = [dataDict objectForKey:#"rating"];
With the following exception detail:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber rangeOfCharacterFromSet:]: unrecognized selector sent to instance 0xb000000000000003'
The dictionary object data looks something like this:
address = "Boston, MA, United States";
"business_id" = 15;
"business_image" = "http://demo.web.com/home-business/upload/user/1420452418_.jpeg";
"business_name" = autodealersma;
lat = "42.3584865";
lng = "-71.06009699999998";
rating = "4.3";
service = "auto dealers";
I think it is because you are trying to set an NSNumber to a text property. The text property needs a NSString. Could you try:
cell.reviewScoreLabel.text = [NSString stringWithFormat:#"%#",[dataDict objectForKey:#"rating"]];
Modify your code to
cell.businessNameLabel.text = [NSString stringWithFormat:#"%#", [dataDict objectForKey:#"business_name"]];
[cell.businessNameLabel setTextColor:[UIColor colorWithRed:1.0/255.0 green:135.0/255.0 blue:68.0/255.0 alpha:1]];
UIFont *customfont = [UIFont fontWithName:#"MyriadPro-Bold" size:16];
[cell.businessNameLabel setFont:customfont];
cell.serviceTypeLabel.text = [NSString stringWithFormat:#"%#",[dataDict objectForKey:#"address"]];
[cell.serviceTypeLabel setTextColor:[UIColor blackColor]];
customfont = [UIFont fontWithName:#"MyriadPro-Regular" size:11];
[cell.serviceTypeLabel setFont:customfont];
cell.businessID = [dataDict objectForKey:#"business_id"];
cell.reviewScoreLabel.text = [NSString stringWithFormat:#"%#",[dataDict objectForKey:#"rating"]];
return cell;
The reason of the crash must be this, the object you are trying to set to your label may not be a NSString. So better take StringValue or format it.
try this ...
cell.businessNameLabel.text = [[dataDict objectForKey:#"business_name"]objectAtIndex:indexPath.row];
[cell.businessNameLabel setTextColor:[UIColor colorWithRed:1.0/255.0 green:135.0/255.0 blue:68.0/255.0 alpha:1]];
UIFont *customfont = [UIFont fontWithName:#"MyriadPro-Bold" size:16];
[cell.businessNameLabel setFont:customfont];
cell.serviceTypeLabel.text = [[dataDict objectForKey:#"address"]objectAtIndex:indexPath.row];
[cell.serviceTypeLabel setTextColor:[UIColor blackColor]];
customfont = [UIFont fontWithName:#"MyriadPro-Regular" size:11];
[cell.serviceTypeLabel setFont:customfont];
cell.businessID = [[dataDict objectForKey:#"business_id"]objectAtIndex:indexPath.row];
cell.reviewScoreLabel.text = [[dataDict objectForKey:#"rating"]objectAtIndex:indexPath.row];
return cell;
Related
I am unable to apply both the attributes at the same. Either only color or subscript am able to apply.
Here is my code
NSMutableAttributedString * attributedText = [[NSMutableAttributedString alloc]initWithString:#"some text"];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Lato-Bold" size:16]
range:NSMakeRange(14,1)];
[attributedText addAttribute:(NSString *)kCTSuperscriptAttributeName value:#-1 range:NSMakeRange(14,1)];
[attributedText addAttribute:(NSString *)kCTForegroundColorAttributeName value:#{ NSForegroundColorAttributeName : [UIColor colorWithRed:85.0/255.0 green:38.0/255.0 blue:152.0/255.0 alpha:1.0] } range:(NSRange){0,6}];
You can try with this code
[str addAttribute:(NSString *)kCTSuperscriptAttributeName value:#-1 range:NSMakeRange(14,1)];
[str setAttributes:#{NSForegroundColorAttributeName:[UIColor greenColor]}
range:(NSRange){0,7}];
Here is an update for your code workable.
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(20, 100, 200, 44)];
[self.view addSubview:textView];
UIColor *color = [UIColor colorWithRed:85.0/255.0 green:38.0/255.0 blue:152.0/255.0 alpha:1.0];
UIFont *font = [UIFont fontWithName:#"Arial" size:20.0];
NSMutableAttributedString * attributedText = [[NSMutableAttributedString alloc]initWithString:#"some text"];
[attributedText addAttribute:NSFontAttributeName
value:[UIFont fontWithName:#"Arial" size:16]//Lato-Bold, Your font name crahes
range:NSMakeRange(8,1)];//x(8) is start index,y(1) is length from start index x(8)
NSDictionary *attrs = #{NSForegroundColorAttributeName : color,NSFontAttributeName:font};
[attributedText addAttributes:attrs range:NSMakeRange(0,6)];//start index start from 0, and length start counting from 1
//[attributedText addAttribute:(NSString *)kCTSuperscriptAttributeName value:#-1 range:NSMakeRange(14,1)];
textView.attributedText = attributedText;
OR
You can try with this.
UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(20, 100, 200, 44)];
NSString *newsTitle = #"Hello";
NSString *sportTtle = #"World";
NSString *title = [NSString stringWithFormat:#"%# %#", newsTitle,sportTtle];
textView.text = title;
UIColor *color = [UIColor redColor];
UIFont *font = [UIFont fontWithName:#"Arial" size:20.0];
NSDictionary *attrs = #{NSForegroundColorAttributeName : color,NSFontAttributeName:font};
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:textView.attributedText];
[attrStr addAttributes:attrs range:[textView.text rangeOfString:sportTtle]];
textView.attributedText = attrStr;
[self.view addSubview:textView];
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.
I have a set of NSString values like this:
self.dataArray = #[#"blue", #"orange", #"green", #"red", #"yellow"];
and would like to be able to do something like (after getting one of the above colors set to self.colorString):
self.view.backgroundColor=[UIColor self.colorString + Color];
but obviously can't do that. What is a possible way?
A nearly universal way:
NSDictionary *colors = #{
#"red": [UIColor redColor],
#"green": [UIColor greenColor],
#"blue": [UIColor blueColor]
};
NSString *name = #"blue";
UIColor *c = colors[name];
A truly universal way:
NSString *selName = [NSString stringWithFormat:#"%#Color", name];
SEL sel = NSSelectorFromString(selName);
UIColor *color = [[UIColor class] performSelector:sel];
You can try something like this:
SEL myColor = NSSelectorFromString([NSString stringWithFormat:#"%#Color", self.colorString]);
self.view.backgroundColor = [[UIColor class] performSelector:myColor]
Try to store associate your data with the colors in a dictionary:
UIColor *blue = [UIColor blueColor];
UIColor *red = [UIColor redColor];
NSDictionary *colors = #{#"blue" : blue, #"red" : red};
UITextField *pinga = [[UITextField alloc]init];
pinga.textColor = [colors objectForKey:#"red"];
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
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;