UITextView undo manager do not work with replacement attributed string (iOS 6) - uitextview

iOS 6 has been updated to use UITextView for rich text editing (a UITextView now earns an attributedText property —which is stupidly non mutable—). Here is a question asked on iOS 6 Apple forum under NDA, that can be made public since iOS 6 is now public...
In a UITextView, I can undo any font change but cannot undo a replacement in a copy of the view's attributed string. When using this code...
- (void) replace: (NSAttributedString*) old with: (NSAttributedString*) new
{
1. [[myView.undoManager prepareWithInvocationTarget:self] replace:new with:old];
2. old=new;
}
... undoing is working well.
But if I add a line to get the result visible in my view, the undoManager do not fire the "replace:with:" method as it should...
- (void) replace: (NSAttributedString*) old with: (NSAttributedString*) new
{
1. [[myView.undoManager prepareWithInvocationTarget:self] replace:new with:old];
2. old=new;
3. myView.attributedText=[[NSAttributedString alloc] initWithAttributedString:old];
}
Any idea? I have the same problem with any of the replacement methods, using a range or not, for MutableAttributedString I tried to use on line "2"...

Umm, wow I really didn't expect this to work! I couldn't find a solution so I just started trying anything and everything...
- (void)applyAttributesToSelection:(NSDictionary*)attributes {
UITextView *textView = self.contentCell.textView;
NSRange selectedRange = textView.selectedRange;
UITextRange *selectedTextRange = textView.selectedTextRange;
NSAttributedString *selectedText = [textView.textStorage attributedSubstringFromRange:selectedRange];
[textView.undoManager beginUndoGrouping];
[textView replaceRange:selectedTextRange withText:selectedText.string];
[textView.textStorage addAttributes:attributes range:selectedRange];
[textView.undoManager endUndoGrouping];
[textView setTypingAttributes:attributes];
}

Mac Catalyst (iOS14)
UITextView has undoManager that will manage undo and redo for free without any additional code.
But replacing its attributedText will reset the undoManager (Updating text and its attributes in textStorage not work for me too). I found that undo and redo will works normally when formatting text without replacing attributedText but by standard edit actions (Right click on highlighting text > Font > Bold (Mac Catalyst)).
So to fix this :
You need to set the allowsEditingTextAttributes of UITextView to be true, this will make UITextView support undo and redo of attributedText.
self.textView.allowsEditingTextAttributes = true
If you want to change the text of attributedText, use replace(_:withText:) of UITextInput, or insertText(_:) and deleteBackward() of UIKeyInput that UITextView conforming to.
self.textView.replace(self.textView.selectedTextRange!, withText: "test")
If you want to change attributes of text, use updateTextAttributes(conversionHandler:) of UITextView instead.
self.textView.updateTextAttributes { _ in
let font = UIFont.boldSystemFont(ofSize: 17)
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
]
return attributes
}
For changing text and its attributes in specific range, modify the selectedRange of UITextView.
To implement undo and redo buttons, check this answer : https://stackoverflow.com/a/50530040/8637708
I have tested with Mac Catalyst, it should work on iOS and iPadOS too.

The Undo Manager is reset after setting its 'text' or 'attributedText' property, this is why it does not work. Whether this behavior is a bug or by design I don't know.
However, you can use the UITextInput protocol method instead.
(void)replaceRange:(UITextRange *)range withText:(NSString *)text
This works.

Related

Is it possible to set custom font & size for NSString?

I'm working with Swift in iOS 9. I want to customize the font for a UIAlertAction. I searched these questions for a Swift answer:
Change the Font of UIAlertAction in Swift
Is it possible to customize the font and appearance of a UIAlertController in the new XCode w/ iOS8?
And this question for an Objective-C answer:
UIAlertController custom font, size, color
But there was no solution for customizing the font for a UIAlertAction.
I believe the problem is that a UIAlertAction uses an NSString for its title property. See demo project on Github.
I would like to create a string like so:
let originalString: String = "OK"
let myString: NSString = originalString as NSString
And then customize the string's font & size. Then after adding my actions to the alert controller, assign the string to my actions using key-value coding:
alertController!.actions[0].setValue(myString, forKey: "title")
But as far as I can tell, there is no way to set a custom font and size for an NSString. If it used a UILabel instead, then it would be easy to customize the font. But I seem to be stuck with the limitations of strings. Does anyone know a way to assign a custom font & size to a string, or am I correct in believing there is no way to do this?
You would use NSAttributedString (or its mutable counterpart, NSMutableAttributedString) to make a string with custom info. As the constructor takes an NSString (or String in Swift), it will not take an NSAttributedString (NSAttributedString isn't a subclass of NSString.).
You could fudge the Swift compiler into passing an NSAttributedString using unsafeBitCast, but UIAlertAction may not like it.
Looking at UIAlertController custom font, size, color, it seems that you can set it using KVO. The code for doing of so is similar:
var alertVC = UIAlertController(title: "Dont care what goes here, since we're about to change below", message: "", preferredStyle: .ActionSheet)
let hogan = NSMutableAttributedString(string: "Presenting the great... Hulk Hogan!")
hogan.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(50), range: NSMakeRange(24, 11))
alertVC.setValue(hogan, forKey: "attributedTitle")

How to hide shortcut bar in iOS9 UIWebview?

I would like to hide bar which is on top of keyboard (undo, redo, copy and back, forward buttons) when user clicks on textfield in UIWebView.
Does anybody know how to do it?
Thanks!
Using method swiziling we can remove the keyboard shortcut bar (only works with ObjC).
- (void)hideKeyboardShortcutBar
{
Class webBrowserClass = NSClassFromString(#"UIWebBrowserView");
Method method = class_getInstanceMethod(webBrowserClass, #selector(inputAccessoryView));
IMP newImp = imp_implementationWithBlock(^(id _s) {
if ([self.webView respondsToSelector:#selector(inputAssistantItem)]) {
UITextInputAssistantItem *inputAssistantItem = [self.webView inputAssistantItem];
inputAssistantItem.leadingBarButtonGroups = #[];
inputAssistantItem.trailingBarButtonGroups = #[];
}
return nil;
});
method_setImplementation(method, newImp);
}
inputAccessoryView
: This property is typically used to attach an accessory view to the
system-supplied keyboard that is presented for UITextField and
UITextView objects.
So the new implementation block will be fired every time the keyboard pops up.
I posted this answer in Hide shortcut keyboard bar for UIWebView in iOS 9 as well
I am able to hide those using these lines
let item:UITextInputAssistantItem = self.textFieldName.inputAssistantItem
item.leadingBarButtonGroups = []
item.trailingBarButtonGroups = []
Hope this will help.

UITextView attributedText and syntax highlighting

Background
So, with iOS 6 an UITextView can take an attributedString, which could be useful for Syntax highlighting.
I'm doing some regex patterns in -textView:shouldChangeTextInRange:replacementText: and oftentimes I need to change the color of a word already typed. I see no other options than resetting the attributedText, which takes time.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
//A context will allow us to not call -attributedText on the textView, which is slow.
//Keep context up to date
[self.context replaceCharactersInRange:range withAttributedString:[[NSAttributedString alloc] initWithString:text attributes:self.textView.typingAttributes]];
// […]
self.textView.scrollEnabled = FALSE;
[self.context setAttributes:self.defaultStyle range:NSMakeRange(0, self.context.length)];
[self refresh]; //Runs regex-patterns in the context
  textView.attributedText = self.context;
self.textView.selectedRange = NSMakeRange(range.location + text.length, 0);
self.textView.scrollEnabled = TRUE;
return FALSE;
}
This runs okayish on the simulator, but on an iPad 3 each -setAttributedText takes a few hundreds of milliseconds.
I filed a bug to Apple, with the request of being able to mutate the attributedText. It got marked as a duplicate, so I cannot see what they're saying about this.
The question
The more specific question:
How can I change the color of certain ranges in a UITextView, with a large multicolored text, with good enough performance to do it in every shouldReplaceText...?
The more broad question:
How do you do syntax highlighting with a UITextView in iOS 6?
I encountered the same problem for my application Zap-Guitar (No-Strings-Attached) where I allow users to type/paste/edit their own songs and the app highlights recognized chords.
Yes it is true apple uses an html writer and parser to display the attributed text. A wonderful explanation of behind the scene can be found here: http://www.cocoanetics.com/2012/12/uitextview-caught-with-trousers-down/
The only solution I found for this problem is not to use attributed text which is an overkill for syntax highlighting.
Instead I reverted to the good old UITextView with plain text and added buttons to the text view where highlighted was needed. To compute the buttons frames I used this answer: How to find position or get rect of any word in textview and place buttons over that?
This reduced CPU usage by 30% (give or take).
Here is a handy category:
#implementation UITextView (WithButtons)
- (CGRect)frameForTextRange:(NSRange)range {
UITextPosition *beginning = self.beginningOfDocument;
UITextPosition *start = [self positionFromPosition:beginning offset:range.location];
UITextPosition *end = [self positionFromPosition:start offset:range.length];
UITextRange *textRange = [self textRangeFromPosition:start toPosition:end];
CGRect rect = [self firstRectForRange:textRange];
return [self convertRect:rect fromView:self.textInputView];
}
#end
The attributedText accessors have to round-trip to/from HTML, so it's really non-optimal for a syntax-highlighted text view implementation. On iOS 6, you'll probably want to use CoreText directly.

HowTo: Visio SDK page Re-Layout FlowChart Top to Bottom

I'm creating a dynamic VSD from a hierarchical set of data that represents a flowchart. I don't want/need to fuddle with absolute positioning of these elements - the automatic layout options will work just fine.
The problem is I can't figure out how to perform this command via code. In the UI (Visio 2010), the commands are on the ribbon here: Design (tab) -> Layout (group) -> Re-Layout (SplitButton).
Any of these will do. Looking through the Visio SDK documentation and Googling for a couple days have turned up nothing of very much use.
Any ideas? (using C#, but VB/VBA would do)
The Page.Layout() method itself is not enough.
In the WBSTreeView.sln sample project (VB.Net) I found how to accomplish this, but couldn't post my answer until 8 hours later :-x
The other layout types are possible by looking through the enums used below.
Compact -> DownRight just ended up being better for most of the flows we're creating.
Translated to C#:
// auto-layout, Compact Tree -> Down then Right
var layoutCell = this._page.PageSheet.get_CellsSRC(
(short)VisSectionIndices.visSectionObject,
(short)VisRowIndices.visRowPageLayout,
(short)VisCellIndices.visPLOPlaceStyle);
layoutCell.set_Result(
VisUnitCodes.visPageUnits,
(short)VisCellVals.visPLOPlaceCompactDownRight);
layoutCell = this._page.PageSheet.get_CellsSRC(
(short)VisSectionIndices.visSectionObject,
(short)VisRowIndices.visRowPageLayout,
(short)VisCellIndices.visPLORouteStyle);
layoutCell.set_Result(
VisUnitCodes.visPageUnits,
(short)VisCellVals.visLORouteFlowchartNS);
//// to change page orientation
//layoutCell = this._page.PageSheet.get_CellsSRC(
// (short)VisSectionIndices.visSectionObject,
// (short)VisRowIndices.visRowPrintProperties,
// (short)VisCellIndices.visPrintPropertiesPageOrientation);
//layoutCell.set_Result(
// VisUnitCodes.visPageUnits,
// (short)VisCellVals.visPPOLandscape);
// curved connector lines
layoutCell = this._page.PageSheet.get_CellsSRC(
(short)VisSectionIndices.visSectionObject,
(short)VisRowIndices.visRowPageLayout,
(short)VisCellIndices.visPLOLineRouteExt);
layoutCell.set_Result(
VisUnitCodes.visPageUnits,
(short)VisCellVals.visLORouteExtNURBS);
// perform the layout
this._page.Layout();
// optionally resize the page to fit the space taken by its shapes
this._page.ResizeToFitContents();
//
Changing Connector Line Colors
If you're unfamiliar with how formulas for colors work, this might also be very frustrating. By default you can give an int as a string to get pre-defined colors, but this isn't very helpful because there isn't an easy way to figure out what each of those colors are. (There is a Page.Colors collection, but you have to inspect each of their RGB values and figure out the color from them.)
Instead, you can use your own RGB values for the formula.
private void SetConnectorLineColor(Shape connector, string colorFormula)
{
var cell = connector.get_Cells("LineColor");
cell.Formula = colorFormula;
}
internal static class AnswerColorFormula
{
public static string Green = "RGB(0,200,0)";
public static string Orange = "RGB(255,100,0)";
public static string Yellow = "RGB(255,200,0)";
public static string Red = "RGB(255,5,5)";
}
Call the Layout method on the Page object. If there are shapes selected on this page then this method will only operate on the current selection. You may want to call DeselectAll on the ActiveWindow first.

LWUIT - show TextField blinking Cursor, even if the field is empty

I have a TextField in a Form. This TextField should have focus by default,
which works fine. Now I'd like the user to be aware of that and show him,
that he's inside the TextField - so the TextField cursor should be shown
and blink.
I only found drawTextFieldCursor in DefaultLookAndFeel. but I have
absolutely no idea how to apply this to my TextField.
Any help - and code would be appreciated!
Here's a sample. I still don't have it working.
public void search2() {
searchForm = new Form();
TextField searchArea = new TextField();
searchForm.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
searchForm.addComponent(searchArea);
searchArea.requestFocus();
int i = Display.getInstance().getKeyCode(Display.GAME_FIRE);
searchArea.keyPressed(i);
searchArea.keyReleased(i);
searchForm.show();
}
What happens is: the TextField is focused, it can be directly edited, the "Abc" mode is shown, but what I really want is to show the user the cursor, so he KNOWS he's inside the TextField. This is not happening... if someone could show me some working code for that...
You want the text field to be in editing mode not for the text field cursor to show (which happens when editing). Use requestFocus() to make sure the text field has focus then use something like:
int i = Display.getInstance().getKeyCode(Display.GAME_FIRE);
tf.keyPressed(i);
tf.keyReleased(i);
The drawTextFieldCursor method has a Graphics parameter , so the way you can draw your cursor is :
derive TextField
in its public void paint(Graphics g) you call drawTextFieldCursor after setting the drawing methods of the TextField's paint Graphic.

Resources