如何从子类UIButton调用viewController中的方法?

时间:2011-05-30 12:23:44

标签: iphone objective-c cocoa-touch uibutton subclass

我试图找到一种识别触摸和按住按钮的方法。我认为将子按钮子类化是一个好主意,但我现在正在努力解决子类,parentsviews和viewcontroller的整个想法。所以请原谅,我担心这是初学者的问题:

如何从子类UIButton调用方法(我在ViewController中定义)?

  • [self someMethod];不起作用 - 因为UIButton不是我的ViewController的后代。
  • [super someMethod];也不起作用 - 我想是同样的问题
  • [self.superview someMethod]; ......再没有运气
  • [MyViewController someMethod];也不起作用 - 因为它'未清除' - 我是否必须导入我的ViewController?或者做某种协议/类调用?

非常感谢任何帮助。

这是我的子类:

        //
    //  MoleButton.h
    //

    #import <Foundation/Foundation.h>


    @interface MoleButton : UIButton {
        int page;
        NSString *colour;

UIViewController *theViewController;

        NSTimer *holdTimer;

    }

    @property (nonatomic, assign) int page;
    @property (nonatomic, assign) NSString *colour;

    @end

    //
//  MoleButton.m

#import "MoleButton.h"


@implementation MoleButton

@synthesize page, colour;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self.superview touchesBegan:touches withEvent:event];

    [holdTimer invalidate];
    holdTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(touchWasHeld) userInfo:nil repeats:NO];

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];
    [self.superview touchesMoved:touches withEvent:event];

    [holdTimer invalidate];
    holdTimer = nil;

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.superview touchesEnded:touches withEvent:event];
} 

- (void)touchWasHeld
{
    holdTimer = nil;
    // do your "held" behavior here

    NSLog(@"TOUCH WAS HELD!!!!");

    [self.theViewController doSomething];

}


@end

2 个答案:

答案 0 :(得分:2)

您可以在子类UIButton类中添加一个属性,该类包含视图控制器。初始化时,您需要添加控制器。

答案 1 :(得分:2)

使用Objective-C的非常简单的委托概念。

在下面的帖子中查看我的答案,以便在Objective-C中使用委托。

How do I set up a simple delegate to communicate between two view controllers?