iOS UI04_Target-Action

來源:互聯網
上載者:User

標籤:ios   target-act   ui   

////  MyButton.h//  UI04_Target-Action////  Created by dllo on 15/8/3.//  Copyright (c) 2015年 zhozhicheng. All rights reserved.//#import <UIKit/UIKit.h>@interface MyButton : UIView//通過MyButton實現button的點擊效果//1.通過自訂的方法,把目標和動作傳到類的內部-(void)addTarget:(id)target Action:(SEL)action;//target:目標,button執行哪一個類的方法,對應的目標就是那個類的對象//action:動作,讓button具體做什麼事,執行的方法就是對應的動作//2.通過兩條屬性,把對應的目標和動作儲存起來@property(nonatomic,assign)id target;@property(nonatomic,assign)SEL action;@end
////  MyButton.m//  UI04_Target-Action////  Created by dllo on 15/8/3.//  Copyright (c) 2015年 zhozhicheng. All rights reserved.//#import "MyButton.h"@implementation MyButton-(void)addTarget:(id)target Action:(SEL)action{    //3.實現對應的自訂方法,並且讓兩個屬性來儲存對應的目標和動作    self.action=action;    self.target=target;}//4.給Button一個觸發的條件,重寫觸摸方法,只要一觸碰touchBegan方法,就會讓button執行相應點擊方法-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    //5.類把他的方法交給MyButton來完成    [self.target performSelector:self.action withObject:self];}@end
////  MainViewController.m//  UI04_Target-Action////  Created by dllo on 15/8/3.//  Copyright (c) 2015年 zhozhicheng. All rights reserved.//#import "MainViewController.h"#import "MyButton.h"@interface MainViewController ()@end@implementation MainViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view.    // 通過UIView來類比一個Button點擊    MyButton *myButton=[[MyButton alloc] initWithFrame:CGRectMake(100, 100, 150, 40)];    myButton.backgroundColor=[UIColor yellowColor];    myButton.layer.borderWidth=1;    myButton.layer.cornerRadius=10;    [self.view addSubview:myButton];    [myButton release];    //6.使用自訂的方法    [myButton addTarget:self Action:@selector(click:)];}-(void)click:(UIButton *)button{    NSLog(@"實現點擊效果");}- (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

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

iOS UI04_Target-Action

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.