如何把iOS代码写的干净整洁

  作为一个coder,看别人写的代码,恐怕都不是一个轻松的工作。那么,如何把代码写的更明了,更简洁?现在稍微把工作中养成的习惯总结一下。

 

  第一,为了不到处引用一些常用的框架,我们最好定义.pch(PreCompiled Headers)文件,然后在设置中添加引用。

 

  第二,能定义成变量的就不要定义成属性了。比如,画面上一个UIButton项目,不需要外部访问,那就在.m文件中直接声明成一个变量吧,安全简洁。

 1 @interface LoginViewController () {
 2     XMPPManager *xmppManager;
 3     CustomTabBarController *tabBarController;
 4     
 5     UIImageView *_accountImageView;
 6     UIImageView *_passwordImageView;
 7     UITextField *_accountTextField;
 8     UITextField *_passwordTextField;
 9     UIButton *_loginButton;
10     SingleLineView *_accountBottomLine;
11     SingleLineView *_passwordBottomLine;
12     UIBarButtonItem *_registItem;
13 }
14 
15 @end

 

  第三,viewDidLoad最好不要写画面项目的初始化这些代码了,单独写一个方法初始化,和属性的写法保持一致;画面项目约束添加在viewWillAppear里,例如:

//
//  LoginViewController.m
//  iChat
//
//  Created by Yunsung on 15/11/24.
//  Copyright © 2015年 wangtao. All rights reserved.
//

#import "LoginViewController.h"
#import "CustomTabBarController.h"

@interface LoginViewController () {
    XMPPManager *xmppManager;
    CustomTabBarController *tabBarController;
    
    UIImageView *_accountImageView;
    UIImageView *_passwordImageView;
    UITextField *_accountTextField;
    UITextField *_passwordTextField;
    UIButton *_loginButton;
    SingleLineView *_accountBottomLine;
    SingleLineView *_passwordBottomLine;
    UIBarButtonItem *_registItem;
}

@end

@implementation LoginViewController

- (void)loadView {
    [super loadView];
    
    // Set background view.
    UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [view setBackgroundColor:[UIColor whiteColor]];
    [self setView:view];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:NSLocalizedString(@"LOGIN_TITLE_CH", nil)];

    // Add subviews.
    [self.view addSubview:self.accountImageView];
    [self.view addSubview:self.accountTextField];
    [self.view addSubview:self.accountBottomLine];
    [self.view addSubview:self.passwordImageView];
    [self.view addSubview:self.passwordTextField];
    [self.view addSubview:self.passwordBottomLine];
    [self.view addSubview:self.loginButton];
    [self.navigationItem setRightBarButtonItem:self.registItem];
    
    xmppManager = [XMPPManager instance];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // Add constraints.
    [_accountImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(30);
        make.top.equalTo(self.view).with.offset(30);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    [_accountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_accountImageView.mas_right).with.offset(20);
        make.right.equalTo(self.view).with.offset(-30);
        make.height.mas_equalTo(@40);
        make.top.equalTo(self.view).with.offset(30);
    }];
    
    [_accountBottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_accountImageView.mas_left).with.offset(0);
        make.right.equalTo(self.view).with.offset(-30);
        make.height.mas_equalTo(@1);
        make.top.equalTo(_accountTextField.mas_bottom).with.offset(2);
    }];
    
    [_passwordImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(30);
        make.top.equalTo(_accountImageView.mas_bottom).with.offset(30);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    [_passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_accountImageView.mas_right).with.offset(20);
        make.right.equalTo(self.view).with.offset(-30);
        make.height.mas_equalTo(@40);
        make.top.equalTo(_accountTextField.mas_bottom).with.offset(30);
    }];
    
    [_passwordBottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_passwordImageView.mas_left).with.offset(0);
        make.right.equalTo(self.view).with.offset(-30);
        make.height.mas_equalTo(@1);
        make.top.equalTo(_passwordTextField.mas_bottom).with.offset(2);
    }];
    
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_passwordTextField.mas_bottom).with.offset(30);
        make.left.equalTo(self.view).with.offset(40);
        make.right.equalTo(self.view).with.offset(-40);
        make.height.mas_equalTo(@40);
    }];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self findFirstResponderBeneathView:self.view] resignFirstResponder];
}

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

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - event response

// Login action
- (void)loginAction:(id)sender {
    [[self findFirstResponderBeneathView:self.view] resignFirstResponder];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [xmppManager connectByUserId:[_accountTextField text] password:[_passwordTextField text]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            tabBarController = [[CustomTabBarController alloc] init];
            [self presentViewController:tabBarController animated:YES completion:nil];
        });
    });
}

// Add edit listener to the text field.
- (void)textFieldEditListener:(id)sender {
    if (_accountTextField.text.length > 0 && _passwordTextField.text.length > 0) {
        [_loginButton setEnabled:YES];
    } else {
        [_loginButton setEnabled:NO];
    }
    
    if (_accountTextField.text.length > 0) {
        [_accountTextField setClearButtonMode:UITextFieldViewModeAlways];
    }
    
    if (_passwordTextField.text.length > 0) {
        [_passwordTextField setClearButtonMode:UITextFieldViewModeAlways];
    }
}

- (void)registAction:(id)sender {
    [xmppManager disconnect];
}

// Close the keyboard.
- (UIView *)findFirstResponderBeneathView:(UIView*)view
{
    // Search recursively for first responder
    for ( UIView *childView in view.subviews ) {
        if ([childView respondsToSelector:@selector(isFirstResponder)] && [childView isFirstResponder])
            return childView;
        UIView *result = [self findFirstResponderBeneathView:childView];
        if (result)
            return result;
    }
    return nil;
}

#pragma mark - getters and setters

- (UIImageView *)accountImageView {
    if (_accountImageView == nil) {
        _accountImageView = [[UIImageView alloc] init];
        [_accountImageView setImage:[[UIImage imageNamed:@"icon_account_number"] imageWithTintColor:[UIColor grayColor]]];
    }
    return _accountImageView;
}

- (void)setAccountImageView:(UIImageView *)accountImageView {
    
}

- (UIImageView *)passwordImageView {
    if (_passwordImageView == nil) {
        _passwordImageView = [[UIImageView alloc] init];
        [_passwordImageView setImage:[[UIImage imageNamed:@"icon_password"] imageWithTintColor:[UIColor grayColor]]];
    }
    return _passwordImageView;
}

- (void)setPasswordImageView:(UIImageView *)passwordImageView {
    
}

- (UITextField *)accountTextField {
    if (_accountTextField == nil) {
        _accountTextField = [[UITextField alloc] init];
        [_accountTextField setDelegate:self];
        [_accountTextField setText:@"wangtao"];
        [_accountTextField setKeyboardType:UIKeyboardTypeAlphabet];
        [_accountTextField addTarget:self action:@selector(textFieldEditListener:) forControlEvents:UIControlEventAllEditingEvents];
        [_accountTextField setPlaceholder:NSLocalizedString(@"ACCOUNT_TEXTFIELD_PLACEHOLDER_CH", nil)];
    }
    return _accountTextField;
}

- (void)setAccountTextField:(UITextField *)accountTextField {
    
}

- (UITextField *)passwordTextField {
    if (_passwordTextField == nil) {
        _passwordTextField = [[UITextField alloc] init];
        [_passwordTextField setSecureTextEntry:YES];
        [_passwordTextField setDelegate:self];
        [_passwordTextField setText:@"admin"];
        [_passwordTextField addTarget:self action:@selector(textFieldEditListener:) forControlEvents:UIControlEventAllEditingEvents];
        [_passwordTextField setPlaceholder:NSLocalizedString(@"PASSWORD_TEXTFIELD_PLACEHOLDER_CH", nil)];
    }
    return _passwordTextField;
}

- (void)setPasswordTextField:(UITextField *)passwordTextField {
    
}

- (UIButton *)loginButton {
    if (_loginButton == nil) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_loginButton setBackgroundColor:[UIColor grayColor]];
        [_loginButton setTintColor:[UIColor whiteColor]];
        [_loginButton setTitle:NSLocalizedString(@"LOGIN_BUTTON_TITLE_CH", nil) forState:UIControlStateNormal];
        [_loginButton.layer setMasksToBounds:YES];
        [_loginButton.layer setCornerRadius:3.f];
        [_loginButton setEnabled:YES];
        [_loginButton addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

- (void)setLoginButton:(UIButton *)loginButton {
    
}

- (SingleLineView *)accountBottomLine {
    if (_accountBottomLine == nil) {
        _accountBottomLine = [[SingleLineView alloc] init];
        [_accountBottomLine setBackgroundColor:[UIColor grayColor]];
    }
    return _accountBottomLine;
}

- (void)setAccountBottomLine:(SingleLineView *)accountBottomLine {
    
}

- (SingleLineView *)passwordBottomLine {
    if (_passwordBottomLine == nil) {
        _passwordBottomLine = [[SingleLineView alloc] init];
        [_passwordBottomLine setBackgroundColor:[UIColor grayColor]];
        [_passwordBottomLine setGridLineWidth:5.f];
        [_passwordBottomLine setGridColor:[UIColor blueColor]];
    }
    return _passwordBottomLine;
}

- (void)setPasswordBottomLine:(SingleLineView *)passwordBottomLine {
    
}

- (UIBarButtonItem *)registItem {
    if (_registItem == nil) {
        _registItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"REGIST_BAR_BUTTON_ITEM_TITLE_CH", nil) style:UIBarButtonItemStylePlain target:self action:@selector(registAction:)];
    }
    return _registItem;
}

- (void)setRegistItem:(UIBarButtonItem *)registItem {
    
}

@end

以上。

posted @ 2015-12-15 13:46  i左撇子  阅读(282)  评论(0编辑  收藏  举报