0

在我的应用程序中,我有一个 UITextView,在 inputAccessory 视图中,我有一些按钮可以让用户输入粗体、斜体等。

当我点击粗体按钮时,我正在添加粗体字体的属性,但 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];
}
4

1 回答 1

0

我想使用setTypingAttributes:可能会帮助你。这里也同样解释。

于 2014-04-02T06:02:09.903 回答