(void)createButton
{
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(100, 100, 100, 50);
[myButton setTitle:@"click me!" forState:UIControlStateNormal];
SEL eventHandler = @selector(clickHandler);
[myButton addTarget:self action:eventHandler forControlEvents:UIControlEventTouchUpInside];
[window addSubview:myButton];
}(void)clickHandler
{
NSLog(@"You clicked button!");
}
自己翻開發者文檔也沒有找到,網上一搜果然已經有人預先想到這個問題了。
最關鍵的一行代碼是
[myButton addTarget:self action:eventHandler forControlEvents:UIControlEventTouchUpInside];
此方法在UIControl類的定義里邊,一開始我在UIbutton里找,沒有找到相關方法,就懷疑是不是在某個父類或者爺爺類里邊,果然,我的直覺還是不錯的,只不過沒想到是UIcontroll類里邊,還是愚蠢。
UIControl里邊定義了一些有關控制的方法,好多控件繼承自它,以后可以多翻翻,說不定有驚喜。