【发布时间】:2015-12-23 19:48:53
【问题描述】:
我正在尝试从 javascript 使用的回调方法调用委托。但是当我从回调执行委托而不是事件触发时,我收到了错误"Can only be called from main thread"。
注意:错误在代码的最后一行。
这是代码的样子
RCT_EXPORT_METHOD(setBold) {
if(_bold == NO)
{
_bold = YES;
}
else if (_bold == YES)
{
_bold = NO;
}
else{
_bold = NO;
}
if(_textV!=nil)
{
_delCalled = YES;
[self textViewDidChangeSelection:_textV];
}
}
-(void)textViewDidChangeSelection:(UITextView *)textView
{
_textV = textView;
_selectedText = [textView.text substringWithRange:textView.selectedRange];
_rangeStart = textView.selectedRange.location;
_rangeEnd = textView.selectedRange.length;
if(_delCalled == YES)
{
[self applyBold:textView];
_delCalled = NO;
}
NSDictionary *event = @{
@"target": textView.reactTag,
@"highlights": @{
@"text": textView.text,
@"range": @(textView.selectedRange.length),
@"cursorPosition": @(textView.selectedRange.location),
@"eventType": @"textViewDidChangeSelection",
}
};
[self.bridge.eventDispatcher sendInputEventWithName:@"topChange" body:event];
}
-(void)applyBold:(UITextView *)textView
{
NSMutableAttributedString *formatString;
UIFont* boldFont;
NSString *selectedText = _selectedText;
_rangeStart -=1;
if(_rangeEnd == 0)
{
_rangeEnd = 1;
}
else
{
_rangeStart +=1;
}
NSRange range = NSMakeRange(_rangeStart, _rangeEnd);
if (_bold==YES) {
boldFont= [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
}
else{
boldFont= [UIFont systemFontOfSize:textView.font.pointSize];
}
NSAttributedString *lem = textView.attributedText;
NSMutableAttributedString *textViewText = [[NSMutableAttributedString alloc]initWithAttributedString:textView.attributedText];
NSDictionary *boldAttr = [NSDictionary dictionaryWithObject:boldFont forKey:NSFontAttributeName];
formatString = [[NSMutableAttributedString alloc]initWithString:selectedText attributes:boldAttr];
if(![selectedText isEqual:@""] || ![selectedText isEqual:@" "])
{
[textViewText replaceCharactersInRange:range withAttributedString:formatString];
//this is where the error happens
textView.attributedText = textViewText;
}
}
【问题讨论】:
标签: javascript ios objective-c react-native