在我的应用程序中我有一个UITextView,在inputAccessory视图中我有一些按钮可以让用户输入Bold,Italics等。
当我点击粗体按钮时,我添加了粗体字体的属性,但UItextView中没有文本,因此所选范围始终为(0,0)。我应该使用什么作为选定的范围,以便我可以以粗体输入即将到来的文本。当我再次点击粗体按钮时,它应该删除粗体字体属性并让用户再次键入普通字体。 这是我正在使用的代码:
-(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];
}