2015年7月12日 星期日

[Objective-C] 模擬UI的事件 - sendActionsForControlEvents

有時候我們可能會需要靠程式碼來觸發UI的事件,像是現在有一個Button,在裡面寫了一些程式碼,可是我不想要等使用者按才觸發,是不是能靠程式碼來觸發呢?

事實上是辦的到的,就是利用sendActionsForControlEvents來達成。

假設現在有二個Button,button1 button2。






















button1的事件是很簡單的印出Log,說我被按了。

而我們要靠button2來觸發button1的事件。

而因為我們必須要取得button1的實體,因此要設定IBOutlet。

最後只要透過button1的sendActionsForControlEvents,就可以完成了。

完整程式碼可以參考下面這個

#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *button;
@end
@implementation ViewController
- (IBAction)buttonClick:(id)sender {
NSLog(@"我是button,我被按了。");
}
- (IBAction)button2Click:(id)sender {
NSLog(@"我是button2,我被按了。");
[self.button sendActionsForControlEvents:UIControlEventTouchUpInside];
//靠程式碼去觸發button的TouchUpInside事件
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
view raw gistfile1.m hosted with ❤ by GitHub
當然還能讓他觸發各式各樣的事件,這裏只是做一個簡略的說明。

這個東西可以讓你測試一些UI事件。

沒有留言:

張貼留言