In my app i have a UITextView and in the inputAccessory view i have a few buttons which can let the user type in Bold, Italics etc.
When I tap the bold button i am adding the attribute for bold font but there is no text in the UItextView so the selected range is always (0,0). What should i use as the selected Range so that i can enter the coming text in Bold. And when i tap the bold button again it should take away the bold font attribute and the let the user type in normal font again. Here's the code i am using :
-(void)addOrRemoveFontTraitWithName:(NSString *)traitName andValue:(uint32_t)traitValue {
NSRange selectedRange = [self.commentsTextView selectedRange];
NSDictionary *currentAttributesDict;
if (selectedRange.location==0 && selectedRange.length==0) {
//currentAttributesDict = [self.commentsTextView.textStorage attributesAtIndex:selectedRange.location effectiveRange:nil];
}
else{
currentAttributesDict = [self.commentsTextView.textStorage attributesAtIndex:selectedRange.location
effectiveRange:nil];
}
UIFont *currentFont;
if (currentAttributesDict.count >0) {
currentFont = [currentAttributesDict objectForKey:NSFontAttributeName];
}
else{
currentFont = [UIFont fontWithName:@"Sans-Regular" size:20.0f];
}
//currentFont = [currentAttributesDict objectForKey:NSFontAttributeName];
UIFontDescriptor *fontDescriptor = [currentFont fontDescriptor];
NSString *fontNameAttribute = [[fontDescriptor fontAttributes] objectForKey:UIFontDescriptorNameAttribute];
UIFontDescriptor *changedFontDescriptor;
if ([fontNameAttribute rangeOfString:traitName].location == NSNotFound) {
uint32_t existingTraitsWithNewTrait = [fontDescriptor symbolicTraits] | traitValue;
changedFontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:existingTraitsWithNewTrait];
}
else{
uint32_t existingTraitsWithoutTrait = [fontDescriptor symbolicTraits] & ~traitValue;
changedFontDescriptor = [fontDescriptor fontDescriptorWithSymbolicTraits:existingTraitsWithoutTrait];
}
UIFont *updatedFont = [UIFont fontWithDescriptor:changedFontDescriptor size:0.0];
NSDictionary *dict = @{NSFontAttributeName: updatedFont};
/*NSMutableDictionary * combined = [[NSMutableDictionary alloc]init];
[combined setObject:updatedFont forKey:NSFontAttributeName];
[combined setObject:[NSNumber numberWithInt:1] forKey:NSUnderlineStyleAttributeName];*/
NSRange newRange = NSMakeRange(0, 10000);
[self.commentsTextView.textStorage beginEditing];
[self.commentsTextView.textStorage setAttributes:dict range:newRange];
[self.commentsTextView.textStorage endEditing];
}