iOS 给Button点击事件添加代理进行传值

2018-05-25  本文已影响38人  隔墙送来秋千影

LoginView.h

#import <UIKit/UIKit.h>

@protocol LoginButtonDelegete <NSObject>

//修饰协议方法  
//@optional--协议方法可实现也可不实现
//@required--协议方法必须实现
@optional

//即协议方法(点击按钮后要做的事情)
- (void) loginWithUserName:(NSString *)userName password:(NSString *)psdStr;

@end

@interface LoginView : UIView
//委托回调接口 用weak描述代理
@property (nonatomic, weak) id <LoginButtonDelegete> loginDelegate;

@end

LoginView.m

- (UIButton *)loginBtn {
    if (!_loginBtn) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginBtn.backgroundColor = BLUE_COLOR;
        _loginBtn.titleLabel.font = kFontSize(14);
        [_loginBtn setTitleColor:WHITE_FONT_COLOR forState:UIControlStateNormal];
        _loginBtn.layer.cornerRadius = 5;
        _loginBtn.clipsToBounds = YES;
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}

//btn点击事件  点击后给Controller传值,用户名和密码,或者用通知传值,此处用代理
- (void) loginBtnClick {
        if ([self.loginDelegate respondsToSelector:@selector(loginWithUserName:password:)]) {
            [self.loginDelegate loginWithUserName:_userID password:_userPsd];
}

LoginViewController.m

#import "LoginViewController.h"
#import "LoginView.h"
//声明协议
@interface LoginViewController ()<LoginButtonDelegete>

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

//遵守协议
- (UIView *)loginView {
    if (!_loginView) {
        _loginView = [[LoginView alloc] initWithViewType:LoginViewType];
        _loginView.loginDelegate = self;
    }
    return _loginView;
}

- (void)setupView{
    self.view = self.loginView;
}

//协议方法 传值
- (void) loginWithUserName:(NSString *)userName password:(NSString *)psdStr {
    [kNotificationCenter addObserver:self selector:@selector(getLoginSucceed:) name:LOGIN_IS_SUCCEED object:nil];
    [[PlatformInterface sharedInstance].loginRegisterInterface requestLoginWithUserName:userName password:psdStr];
}
上一篇下一篇

猜你喜欢

热点阅读