Search code examples
iosobjective-cxcodeuitoolbar

Subclass tool bar


I added a toolbar on top of the keyboard, it appears every-time the user clicks on a TextView, it also has a number of buttons that change and interact with the TextView, like for example, changing the text font.

What I'm trying to do now is to create a subclass of the Toolbar so that it can be used on other TextViews, but my problem is:

How to use the TextView delegate methods from inside the Toolbar subclass?

Here is my current code(not all code, for not making the post too big):

.h

#import <UIKit/UIKit.h>

@interface CustomUIToolbar : UIToolbar{
    UIButton *btn1;
    UIButton *btn2;
    UIButton *btn3;
}

.m

@implementation CustomUIToolbar

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        UIBarButtonItem *one = ...
        UIBarButtonItem *two = ...
        UIBarButtonItem *three = ...

        self.barStyle = UIBarStyleDefault;
        self.layer.borderWidth = 1;
        self.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        self.items = [NSArray arrayWithObjects:one,placeholder,two,three,four,five,nil];
        [self sizeToFit];
    }
    return self;
}

-(void)actionBtn3:(UIButton *) barBtnItem{
    ...
}

-(void)actionBtn2:(UIButton *) barBtnItem{
    ...
}

-(void)actionBtn1:(UIButton *) barBtnItem{
    ...
}

// And the UITextView Delegate Methods

- (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  ...
  return YES;
}

- (void)textViewDidChangeSelection:(UITextView *)textView {
  ...
}

Solution

  • Your CustomUIToolbar class should conform to UITextViewDelegate protocol:

    @interface CustomUIToolbar : UIToolbar <UITextViewDelegate> {
    

    Then you need to assign your CustomUIToolbar subclass as a delegate to textView:

    self.textView.delegate = self.customTabbar;
    

    Update:

    I think the problem because your toolbar instance is released before the delegate method is called on it. Try to make a property to make sure that variable stays in memory. So instead of:

    UIToolbar *tool = [[CustomUIToolbar alloc] init];
    

    Create a property:

    @property(nonatomic, strong) CustomUIToolbar *tool;
    

    And initialize it:

    self.tool = [[CustomUIToolbar alloc] init];