0

I created a subclass of UITextView to add a custom UIMenuItem. The problem is that when I press my custom action to display custom item, the text is not highlighted. Any idea?

enter image description here

ActionsTextView.h

#import <UIKit/UIKit.h>

@protocol ActionsDelegate <NSObject>

- (void)addDreamSignalWithText:(NSString *)text range:(NSRange)range;

@end

@interface ActionsTextView : UITextView

#pragma mark - Delegate
@property IBOutlet id<ActionsDelegate>actionsDelegate;

#pragma mark - Methods
- (void)addDreamSignalAction:(id)sender;

@end

ActionsTextView.m

#import "ActionsTextView.h"

@implementation ActionsTextView

- (BOOL)canBecomeFirstResponder {

    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {

    if (action == @selector(addDreamSignalAction:)) {
        return YES;
    }

    return NO;

}

#pragma mark - Methods
- (void)addDreamSignalAction:(id)sender {

    if ([_actionsDelegate respondsToSelector:@selector(addDreamSignalWithText:range:)]) {
        [_actionsDelegate addDreamSignalWithText:[self.text substringWithRange:self.selectedRange]
                                           range:self.selectedRange];
    }

    // Deselect text
    self.selectedTextRange = nil;

}


@end

Thanks!!

mhergon
  • 1,688
  • 1
  • 18
  • 39

1 Answers1

0

Thanks to rmaddy, I found the solution. Here is the code:

ActionsTextView.h

#import <UIKit/UIKit.h>

@protocol ActionsDelegate <NSObject>

- (void)addDreamSignalWithText:(NSString *)text range:(NSRange)range;

@end

@interface ActionsTextView : UITextView

#pragma mark - Delegate
@property IBOutlet id<ActionsDelegate>actionsDelegate;

#pragma mark - Methods
- (void)addDreamSignalAction:(id)sender;

#pragma mark - Notifications
- (void)menuControllerWillShow:(NSNotification *)notification;

@end

ActionsTextView.m

#import "ActionsTextView.h"

@implementation ActionsTextView

- (BOOL)canBecomeFirstResponder {

    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {

    if (action == @selector(addDreamSignalAction:)) {
        return YES;
    }

    return NO;

}

#pragma mark - Methods
- (void)addDreamSignalAction:(id)sender {

    if ([_actionsDelegate respondsToSelector:@selector(addDreamSignalWithText:range:)]) {
        [_actionsDelegate addDreamSignalWithText:[self.text substringWithRange:self.selectedRange]
                                           range:self.selectedRange];
    }

    // Deselect text
    self.selectedTextRange = nil;

}

#pragma mark - Notifications
- (void)menuControllerWillShow:(NSNotification *)notification {

    if (self.selectedRange.length == 0) {

        [self select:self];

    }

}

@end
mhergon
  • 1,688
  • 1
  • 18
  • 39