2011-05-30 74 views
0

我试图找到一种方法来识别我的按钮上的触摸&。我认为子类化我的按钮是一个好主意,但我现在正在努力处理子类,父视图和视图控制器的整个想法。所以请原谅,我担心这是一个初学者的问题:如何从子类UIButton调用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

你可以简单地在子类UIButton的类,它保存视图控制器添加属性。初始化它时,你肯定需要添加控制器。

+0

感谢这么多,但究竟如何做呢? @property(nonatomic,retain)ViewController MyViewController?我是否通过#importing添加控制器? – 2011-05-30 12:30:07

+1

你已经在你的子类UIButton中创建了属性。添加另一个(UIViewController * myViewController),在初始化Button之后,添加viewController([yourbutton setMyViewController:self];并用[self.myViewConroller yourMessage]在你的UIButton子类中调用它; – cem 2011-05-30 12:32:27

+0

非常感谢,但我没有得到这个工作。我现在得到错误消息'访问未知的viewController getter方法,当我调用[self.theViewController doSomething]; – 2011-05-30 13:03:43

2

使用非常简单的代表 Objective-C的概念。

检查我的答案在下面的帖子中使用Objective-C中的委托。

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

+1

这是一种更清洁的方法,它不会将你的按钮绑定到你的视图控制器,您有机会稍后再使用它。 – 2011-05-30 12:36:55

+0

@Deepak:谢谢......但我很头痛,想要理解这一点......这并不是我想要的那么简单。也许我需要更多时间来解决这个问题。就目前而言,我坚持使用未安装的显然是“不干净”的方法。 – 2011-05-30 13:27:29

+1

@ n.evermind:委托概念是在Objective-C编程中广泛使用的东西,如果你花一些时间去理解它并在许多情况下对你有帮助,那将会更好。 – Jhaliya 2011-05-30 13:46:06