問題描述
UITextView tidak mengaktifkan textViewDidChange pada perubahan atribut? (UITextView not firing textViewDidChange on attribute change?)
I have a UITextView
configured with a delegate. I've enabled editing attributes by setting allowsEditingTextAttributes
to YES
.
When the user types a character in the text view, the delegate receives the textViewDidChange
: message.
But when the user changes an attribute (such as making a selection and tapping Bold or Italic), no textViewDidChange
: message.
The documentation specifically says that textViewDidChange
: should receive a message when the user changes attributes:
Tells the delegate that the text or attributes in the specified text view were changed by the user.
But it's not working for me. What am I missing here?
‑‑‑‑‑
參考解法
方法 1:
I tested this scenario in iOS 6 and had the exact same outcome: attribute changes from the "select" pop‑up did not trigger the textViewDidChange:
method. It seems that this is a bug or the documentation needs to clarify what type of attribute change would trigger this event.
A possible workaround is to implement the textViewDidChangeSelection:
method. It gets called whenever a selection is made (which the user would have to do before changing an attribute). Check to see if the selectedRange.length is > 0 (which would mean an actual word has been selected, instead of just moving the cursor around), and save that selectedRange. Once the length is zero again, it means they deselected the item. At that time, you could take the previous range and work with the text.
‑ (void)textViewDidChangeSelection:(UITextView *)textView
{
static BOOL rangeSet = NO;
static NSRange mySelectedRange;
if( textView.selectedRange.length > 0 && !rangeSet )
{
mySelectedRange = textView.selectedRange;
rangeSet = YES;
}
else if( textView.selectedRange.length == 0 && rangeSet)
{
// Work with text
NSLog(@"Working with previously select text: %d, %d", mySelectedRange.location, mySelectedRange.length);
}
}
方法 2:
In documentation it has also been mentioned that
This method is not called in response to programmatically initiated changes
So if you are setting bold or italic programatically so it will not invoke this delegate method
方法 3:
Please check if you've set UITextViewDelegate in in your .h file. Also you'll have to `make
yourTextView.delegate = self
So that your Text View will give control to your current class.
方法 4:
I got around this by subclassing UITextView, overriding the toggleBoldface:
, toggleItalics:
and toggleUnderline:
methods, and calling [self.delegate textViewDidChange:self]
from those methods. This answer helped me figure that out.
(by stevex、J Shapiro、Sunil Pandey、Rushi、arlomedia)