Переслать событие из пользовательского подкласса UIControl - PullRequest
4 голосов
/ 24 мая 2010

Мой пользовательский подкласс расширяет UIControl (EditableImageView) В основном он содержит 3 подпредставления:

  • UIButton (UIButtonTypeCustom)
  • UIImageView
  • UILabel

Весь класс работает отлично, но теперь я хочу связать некоторые события, сгенерированные из этого класса, с другим. В частности, при нажатии кнопки, я хочу переслать событие владельцу viewcontroller, чтобы я мог обработать событие. Проблема в том, что я не могу понять, как реализовать это поведение. В EditableImageView я могу поймать событие касания, используя [button addTarget: self action: @selector (buttonPressed :) forControlEvents: UIControlEventTouchUpInside], но я не знаю, как переслать его внутри селектора buttonPressed. Я также пытался реализовать touchSegan, но, кажется, никогда не вызывал ...

Я бы хотел зафиксировать событие нажатия кнопки в контроллере вида следующим образом:

- (void)viewDidLoad {
[super viewDidLoad];

self.imageButton = [[EditableImageView alloc] initWithFrame:CGRectMake(50.0f, 50.0f, 80.0f, 80.0f)];
[imageButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:imageButton];
[imageButton setEditing:NO];

}

Это мой метод инициализации подкласса UIControl:

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

        button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0.0f, 0.0f, frame.size.width, frame.size.height);
        [button setImage:[UIImage imageNamed:@"nene_70x70.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:button];

        transparentLabelBackground = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"editLabelBackground.png"]];
        transparentLabelBackground.hidden = YES;
        [self addSubview:transparentLabelBackground];

        // create edit status label
        editLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        editLabel.hidden = YES;
        editLabel.userInteractionEnabled = NO;  // without this assignment the button will not be clickable
        editLabel.textColor = [UIColor whiteColor];
        editLabel.backgroundColor = [UIColor clearColor];
        editLabel.textAlignment = UITextAlignmentLeft;
        UIFont *labelFont = [UIFont systemFontOfSize:16.0];
        editLabel.font = labelFont;     
        editLabel.text = @"edit"; 
        labelSize = [@"edit" sizeWithFont:labelFont];

        [self addSubview:editLabel];
    }

    return self;
}

Спасибо.

1 Ответ

6 голосов
/ 25 мая 2010

Я решил так:

EditableImageView.h:

@interface EditableImageView : UIControl {
UIButton *button;
UIImageView *transparentLabelBackground;
UILabel *editLabel;
CGSize labelSize;

BOOL editing;
}

@property (nonatomic, retain) UIButton *button;
@property (nonatomic, retain) UILabel *editLabel;
@property (nonatomic, retain) UIImageView *transparentLabelBackground;
@property (nonatomic, getter=isEditing) BOOL editing;

- (void)buttonPressed:(id)sender;
@end

EditableImageView.m:

 (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setBackgroundColor:[UIColor clearColor]];

        button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0.0f, 0.0f, frame.size.width, frame.size.height);
        [button setImage:[UIImage imageNamed:@"nene_70x70.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
        .......
    }
}


- (void)buttonPressed:(id)sender {
[self sendActionsForControlEvents:UIControlEventTouchUpInside];
}

MyController.m:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.imageButton = [[EditableImageView alloc] initWithFrame:CGRectMake(50.0f, 50.0f, 80.0f, 80.0f)];
    [imageButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:imageButton];
}

- (void)buttonPressed:(id)sender {
    NSLog(@"buttonPressed!");
}
...