OC常用代码记录(UI)

2017-10-13  本文已影响0人  Look2021

---------------UIWindow-------------

[self.window makeKeyWindow];
UIWindow *window = [UIApplication sharedApplication].keyWindow;

if ([GHUserService service].accessToken) {
    //跳过登陆
    GHBaseNavigationController *vc = [GHBaseNavigationController gh_navigationController];
    window.rootViewController = vc;
} else {
    GHLoginViewController *loginVc = [[GHLoginViewController alloc] init];
    UINavigationController *loginNavVc = [[UINavigationController alloc] initWithRootViewController:loginVc];
    [loginNavVc setNavigationBarHidden:YES];
    window.rootViewController = loginNavVc;
}    

---------------NavigationController---------------

//重写返回键
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.childViewControllers.count > 0) {
        viewController.hidesBottomBarWhenPushed = YES;
        
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [backBtn setImage:[UIImage imageNamed:@"back_homepage_icon"] forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(onClickBack:) forControlEvents:UIControlEventTouchUpInside];
        [backBtn sizeToFit];
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
        viewController.navigationItem.leftBarButtonItem = leftItem;
    }
    [super pushViewController:viewController animated:animated];
}
- (void)onClickBack:(UIButton *)sender {
    [self popViewControllerAnimated:YES];
}
#pragma mark - UIGestureRecognizerDelegate
// 防止在根视图滑动手势后,界面卡死
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return self.childViewControllers.count > 1;
}

// 在需要禁用右滑pop手势的ViewController中加入以下代码
    id target = self.navigationController.interactivePopGestureRecognizer.delegate;
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:target action:nil];
    [self.view addGestureRecognizer:pan];

// 重写返回按钮
- (void)backButtonItem {
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"back_homepage_icon"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(dismissController:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn sizeToFit];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    self.navigationItem.leftBarButtonItem = leftItem;
}

// 根据image设置ButtonItem
self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"icon_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftButton)];

// 根据Button设置ButtonItem
UIButton *rightBtn = [[UIButton alloc] init];
[rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
[rightBtn setTitleColor:k_Color_354261 forState:UIControlStateNormal];
[rightBtn setTitle:@"取消" forState:UIControlStateSelected];
[rightBtn setTitleColor:k_Color_999999 forState:UIControlStateSelected];
            [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            self.rightBtn = rightBtn;
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];

//在各个控制器控制tabBar和navigationBar
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBarHidden = YES;
}

---------------UIView---------------

//给view添加手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(coopTypeLabSwitchAction)];
        [_coopTypeTipsLab addGestureRecognizer:tap];

// 通过tag获取view
UIButton *btn = (UIButton *)[self.view viewWithTag:sender.tag];

---------------UITableView---------------

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        [self.view addSubview:self.tableView];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"GHAppiontmentCell" bundle:nil] forCellReuseIdentifier:SweeperAppointmentcellID];
    }
    return _tableView;
}

#pragma mark ------- TableViewDelegate, TableViewDataSource -------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 65;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GHAppiontmentCell *cell = [tableView dequeueReusableCellWithIdentifier:SweeperAppointmentcellID];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    GHTimerInfoModel *model = self.dataArr[indexPath.row];
    [cell confignAppiontmentCellWithTimerInfoModel:model];
    return cell;
}

//隐藏tableView自带的分割线
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//想隐藏没用到的cell的分割线,可以直接粗暴的加上尾视图
self.tableView.tableFooterView = [UIView new];
//设置分割线颜色
[tableview  setSeparatorColor:[UIColor blueColor]];
//设置cell可以选择
[self.collectTableView setEditing:YES animated:YES];

//根据cell, 刷新cell
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self.tableView reloadRowsAtIndexPaths:indexPath withRowAnimation:UITableViewRowAnimationNone];

// 用storyboard创建UITableViewController
+ (instancetype)gh_sweepermanagement {
    return [[UIStoryboard storyboardWithName:NSStringFromClass(self) bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass(self)];
}

//tableview既要有左滑删除又要有全选删除
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (self.collectTableView.editing) {
        return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
    }else{
        return UITableViewCellEditingStyleDelete;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *GHHomePageDVcellID = @"GHHomePageDVcellID";
    GHHomePageDVcell *cell = [tableView dequeueReusableCellWithIdentifier:GHHomePageDVcellID];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"GHHomePageDVcell" owner:nil options:nil] firstObject];
    }
    
    return cell;
}
tableViewCell
//cell选中没有效果
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[tableView deselectRowAtIndexPath:indexPath animated:NO];
//改变全选cell,左边的选中颜色
cell.tintColor = [UIColor orangeColor];

//改变cell的背景颜色(选择cell的颜色)
UIView *backgroundViews = [[UIView alloc]initWithFrame:cell.frame];
backgroundViews.backgroundColor = [UIColor whiteColor];
[cell setSelectedBackgroundView:backgroundViews];

---------------UITextField---------------

_questionTypeTF.rightView = rightImageView;
_questionTypeTF.rightViewMode = UITextFieldViewModeAlways;

---------------UIImageView---------------

// 图片填充模式
rightImageView.contentMode =  UIViewContentModeRight;

---------------UIButton---------------

// 文字和图片都靠左显示
backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//leffBtn
    UIImage *leftImage = [[UIImage imageNamed:@"drawer_homepage_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftBtnClick:)];
// rightBtn
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    self.navigationItem.rightBarButtonItem.tintColor = k_Color_333333;

//圆角
- (UIButton *)extractBtn
{
    if (!_extractBtn) {
        _extractBtn = [[UIButton alloc] init];
        _controlBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_blueView addSubview:_extractBtn];
        [_extractBtn setTitle:NSLocalizedString(@"ED_Mine_MyWallet_Withdrawals", @"提现") forState:UIControlStateNormal];
        _extractBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        _extractBtn.titleLabel.font = kFont_Button;
        _extractBtn.backgroundColor = [UIColor whiteColor];
        [_extractBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [selectedBtn setTitle:@"取消全选" forState:UIControlStateSelected];
        [selectedBtn setTitle:@"全选" forState:UIControlStateNormal];
        [selectedBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [selectedBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        [_extractBtn addTarget:self action:@selector(extractBtnClick) forControlEvents:UIControlEventTouchUpInside];
        //圆角
        [_extractBtn.layer setCornerRadius:22];
        //阴影
        _extractBtn.layer.shadowOffset = kAppUICon_BtnShadowOffset;
        _extractBtn.layer.shadowOpacity = 0.2;
        _extractBtn.layer.shadowColor = [UIColor blackColor].CGColor;
        //画边框线
        [extractBtn.layer setBorderColor:S07_App_LineColor.CGColor];
        [extractBtn.layer setBorderWidth:1];
        [extractBtn.layer setMasksToBounds:YES];
        
        [_extractBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(kAppUICon_LeftSpace);
            make.right.equalTo(kAppUICon_RightSpace);
            make.bottom.equalTo(_blueView.mas_bottom).offset(kAppUICon_BtnHeight / 2);
            make.height.mas_equalTo(kAppUICon_BtnHeight);
        }];
    }
    return _extractBtn;
}

//使图片和文字水平居中显示
self.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
//文字距离上边框的距离增加imageView的高度,距离左边框减少imageView的宽度,距离下边框和右边框距离不变
[self setTitleEdgeInsets:UIEdgeInsetsMake(self.imageView.frame.size.height + 20 ,-self.imageView.frame.size.width, 0.0,0.0)];
//图片距离右边框距离减少图片的宽度,其它不边
[self setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0,10, -self.titleLabel.bounds.size.width)];

---------------UISwitch---------------

    self.modelSwitch.transform = CGAffineTransformMakeScale(0.6, 0.6);
    self.modelSwitch.tintColor = k_Color_EBEBEB;
    self.modelSwitch.backgroundColor = k_Color_EBEBEB;
    self.modelSwitch.layer.cornerRadius = (self.modelSwitch.frame.size.height / 0.6) / 2.0;
    self.modelSwitch.layer.masksToBounds = YES;

---------------UILabel---------------

动态改变label的宽度,改变label的部分字符
_groupName.text = [NSString stringWithFormat:@"%@ (%li)",_ref.groupName,_ref.count];
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:_groupName.text];
    // 需要改变的第一个文字的位置
    NSUInteger firstLoc = [[noteStr string] rangeOfString:@"("].location;
    // 需要改变的最后一个文字的位置
    NSUInteger secondLoc = [[noteStr string] rangeOfString:@")"].location + 1;
    // 需要改变的区间
    NSRange range = NSMakeRange(firstLoc, secondLoc - firstLoc);
    // 改变颜色
    [noteStr addAttribute:NSForegroundColorAttributeName value:S04_App_SubCharColor range:range];
    // 改变字体大小及类型
    [noteStr addAttribute:NSFontAttributeName value:P26_TagAssistFont range:range];
    // 为label添加Attributed
    [_groupName setAttributedText:noteStr];

---------------UIScrollview---------------

scrollView.showsHorizontalScrollIndicator = false;//不要滚动效果横杠
scrollView.showsVerticalScrollIndicator = false;//不要滚动效果竖杠

https://blog.csdn.net/science_Lee/article/details/54315341

---------------UICollectionView---------------

UICollectionViewController

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake((kSCREEN_WIDTH - 15 * 2) /2, kAdaptedHeight(180));
        layout.minimumLineSpacing = 5;// 最小行间距
        layout.minimumInteritemSpacing = 5;// 最小列间距
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
        
        [self.view addSubview:_collectionView];
        _collectionView.backgroundColor = k_Color_WhiteColor;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        
        [self.collectionView registerClass:[GHExplorationCenterCell class] forCellWithReuseIdentifier:NSStringFromClass([GHExplorationCenterCell class])];
    }
    return _collectionView;
}

//定义每个Section的四边间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(15, 15, 5, 15);//分别为上、左、下、右
}

UICollectionViewCell

实现UICollectionViewCell自适应文字宽度
https://blog.csdn.net/lvlemo/article/details/76607073

CollectionViewDelegate

头部控件需要继承UICollectionReusableView,只会跑initWithFrame方法
[self.collectionView registerClass:[RDBookcaseReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:RDBookcaseReusableViewID];
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    CGSize size = CGSizeMake(kSCREEN_WIDTH, 200);
    return size;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableview = nil;
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        // 头部视图
        RDBookcaseReusableView *tempReusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:RDBookcaseReusableViewID forIndexPath:indexPath];
        reusableview = tempReusableView;
    }
    return reusableview;
}

---------------UITextField---------------

https://www.jianshu.com/p/740cd34f870b

[_nameTextFile resignFirstResponder];//退出键盘
[_nameTextFile becomeFirstResponder];//弹出键盘
//键盘
_bankTextF.keyboardType = UIKeyboardTypeNumberPad;
self.passwordTF.autocorrectionType = UITextAutocorrectionTypeNo;// 关闭拼写自动提示

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    /*
     * 不能输入.0-9以外的字符。
     * 设置输入框输入的内容格式
     * 只能有一个小数点
     * 小数点后最多能输入两位
     * 如果第一位是.则前面加上0.
     * 如果第一位是0则后面必须输入点,否则不能输入。
     * 协作费用一次最多不能支付超10000元
     */
    
    // 判断是否有小数点
    if ([textField.text containsString:@"."]) {
        self.isPoint = YES;
    }else{
        self.isPoint = NO;
    }
    
    if (string.length > 0) {
        
        //当前输入的字符
        unichar single = [string characterAtIndex:0];
        NSLog(@"single = %c",single);
        
        // 不能输入.0-9以外的字符
        if (!((single >= '0' && single <= '9') || single == '.'))
        {
            [SVProgressHUD showMsgWithStatus:@"您的输入格式不正确" delay:1];
            return NO;
        }
        
        // 只能有一个小数点
        if (self.isPoint && single == '.') {//最多只能输入一个小数点
            return NO;
        }
        
        // 如果第一位是.则前面加上0.
        if ((textField.text.length == 0) && (single == '.')) {
            textField.text = @"0";
        }
        
        // 如果第一位是0则后面必须输入点,否则不能输入。
        if ([textField.text hasPrefix:@"0"]) {
            if (textField.text.length > 1) {
                NSString *secondStr = [textField.text substringWithRange:NSMakeRange(1, 1)];
                if (![secondStr isEqualToString:@"."]) {//第二个字符需要是小数点
                    return NO;
                }
            }else{
                if (![string isEqualToString:@"."]) {//第二个字符需要是小数点
                    return NO;
                }
            }
        }
        
        // 小数点后最多能输入两位
        if (self.isPoint) {
            NSRange ran = [textField.text rangeOfString:@"."];
            // 由于range.location是NSUInteger类型的,所以这里不能通过(range.location - ran.location)>2来判断
            if (range.location > ran.location) {
                if ([textField.text pathExtension].length > 1) {//小数点后最多有两位小数
                    return NO;
                }
            }
            //不超过5位数
            if (textField.text.length > 7) {
                return NO;
            }
        } else {
            //不超过5位数
            if (textField.text.length > 4) {
                return NO;
            }
        }
    }
    return YES;
}

--------------UIAlertController---------------

//创建性别选择
- (void)creatAlertControllerSheet {
    
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:MyString(@"Gender") message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *actionMale = [UIAlertAction actionWithTitle:MyString(@"Male") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *actionFemale = [UIAlertAction actionWithTitle:MyString(@"Female") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:MyString(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [actionSheet addAction:actionMale];
    [actionSheet addAction:actionFemale];
    [actionSheet addAction:actionCancel];
    [self presentViewController:actionSheet animated:YES completion:nil];
}

---------------CABasicAnimation---------------

_electricityLayer = [CAShapeLayer layer];
// 设置圆心坐标,设置圆的半径,设置画圆弧度起始角度,设置画圆弧度结束角度,是否顺时针画圆
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithArcCenter:self.sweeperImageView.center radius:112 + progressWidth / 2 startAngle:3 * M_PI / 2 endAngle:3 * M_PI / 2 * 1.00001 clockwise:NO];
    self.electricityLayer.frame = self.sweeperImageView.bounds;
    self.electricityLayer.fillColor = k_Color_ClearColor.CGColor;// 填充颜色
    self.electricityLayer.strokeColor = k_Color_10CD13.CGColor;// 线条颜色
    self.electricityLayer.lineWidth = progressWidth;
    self.electricityLayer.path = bezierPath.CGPath;
    self.electricityLayer.strokeStart = 0.f;
    self.electricityLayer.strokeEnd = 0.f;
    [self.sweeperImageView.layer addSublayer:self.electricityLayer];

// 充电动画
- (void)sweeperChargeAnimation {
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 2.0;
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue = [NSNumber numberWithFloat:1.f];
    pathAnimation.repeatCount = HUGE_VALF;
    //使视图保留到最新状态
    pathAnimation.removedOnCompletion =YES;
    pathAnimation.fillMode =kCAFillModeForwards;
    [self.electricityLayer addAnimation:pathAnimation
                                 forKey:nil];
}
上一篇下一篇

猜你喜欢

热点阅读