target-action設計模式--主要為Button的方法重寫

來源:互聯網
上載者:User

標籤:interface   property   action   frame   target   

建立兩個類MainViewController/ButtonView

ButtonView.h

#import <UIKit/UIKit.h>@interface ButtonView : UIView//實現target-action設計模式//點擊的時候讓誰去執行方法@property (nonatomic , assign) id target;//要執行的方法@property (nonatomic , assign) SEL action;//類比一個UIButton的一個方法- (void)addTarget:(id)target action:(SEL)action;@end

ButtonView.m

#import "ButtonView.h"@implementation ButtonView- (id)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {        // Initialization code    }    return self;}//建立一個view,讓這個view的作用和UIButton類似 作用;點擊能夠響應事件- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    //點擊時候就有反應        }- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{    NSLog(@"摸完了,可口可樂,冒泡");        //每當view被點擊的時候,就讓target執行action方法    //target\action設計模式核心    [_target performSelectorInBackground:self.action withObject:self];}//利用方法給view設定對象和對象要執行的方法- (void)addTarget:(id)target action:(SEL)action{    self.target = target;    self.action = action;}/*// Only override drawRect: if you perform custom drawing.// An empty implementation adversely affects performance during animation.- (void)drawRect:(CGRect)rect{    // Drawing code}*/@end

MainViewController.h

#import <UIKit/UIKit.h>@interface MainViewController : UIViewController@end

MainViewController.m

#import "MainViewController.h"#import "ButtonView.h"@interface MainViewController ()@end@implementation MainViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];    if (self) {        // Custom initialization    }    return self;}- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view.        ButtonView *button = [[ButtonView alloc] initWithFrame:CGRectMake(120, 50, 80, 30)];    button.backgroundColor = [UIColor purpleColor];    button.alpha = 0.3;    button.layer.cornerRadius = 10;    //給view添加一個觸發方法    [button addTarget:self action:@selector(buttonClicked:)];        [self.view addSubview:button];    [button release];        //UIImageView      //是一個顯示圖片的view    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];    [self.view addSubview:imageView];    [imageView release];    //給imageView設定一個顯示的圖片    UIImage *image = [UIImage imageNamed:@"1.png"];    imageView.image = image;    //如果在imageView 上添加按鈕等視圖,需要開啟imageView的使用者互動屬性    [imageView setUserInteractionEnabled:YES];        UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(160, 100, 50, 50)];    [self.view addSubview:imageView1];    [imageView1 release];    UIImage *image1 = [UIImage imageNamed:@"2.png"];    imageView1.image = image1;    }- (void)buttonClicked:(ButtonView *)button{    NSLog(@"button觸發後的方法");}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}/*#pragma mark - Navigation// In a storyboard-based application, you will often want to do a little preparation before navigation- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{    // Get the new view controller using [segue destinationViewController].    // Pass the selected object to the new view controller.}*/@end


AppDelegate.h

#import <UIKit/UIKit.h>@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;@end

AppDelegate.m

#import "AppDelegate.h"#import "MainViewController.h"@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    // Override point for customization after application launch.    self.window.backgroundColor = [UIColor whiteColor];    //初始化視圖控制器    MainViewController *mainVC = [[MainViewController alloc] init];    self.window.rootViewController = mainVC;    [mainVC release];            [self.window makeKeyAndVisible];            [_window release];    return YES;}- (void)dealloc{    [_window release];    [super dealloc];}- (void)applicationWillResignActive:(UIApplication *)application{    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.}- (void)applicationDidEnterBackground:(UIApplication *)application{    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.}- (void)applicationWillEnterForeground:(UIApplication *)application{    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.}- (void)applicationDidBecomeActive:(UIApplication *)application{    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.}- (void)applicationWillTerminate:(UIApplication *)application{    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.}@end



本文出自 “小劉_Blog” 部落格,請務必保留此出處http://liuyafang.blog.51cto.com/8837978/1548166

target-action設計模式--主要為Button的方法重寫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.