iOS开发常用UI小技巧

整理一下开发中常用的UI小技巧

  1. UINavigationBar相关设置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // 去阴影
    [[UINavigationBar appearance] setShadowImage:[UIImage new]];
    // 设置标题
    NSMutableDictionary *titleTextAttrs = [NSMutableDictionary dictionary];
    titleTextAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
    titleTextAttrs[NSFontAttributeName] = [UIFont boldSystemFontOfSize:18];
    [[UINavigationBar appearance] setTitleTextAttributes:titleTextAttrs];
    // 设置渲染色
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    // 设置背景图片
    [[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"navc_bg_blue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forBarMetrics:UIBarMetricsDefault];
  2. UITabBar相关设置

    1
    2
    3
    4
    5
    // 去阴影
    [[UITabBar appearance] setShadowImage:[UIImage new];
    // 更换系统自带的tabbar
    DHTabBar *tabBar = [DHTabBar tabbar];
    [self setValue:tabBar forKeyPath:@"tabBar"];
  3. UITabBarController
    选中不同控制器显示不同的statusBar样式

    1
    2
    3
    4
    - (UIStatusBarStyle)preferredStatusBarStyle
    {
    return self.selectedViewController.preferredStatusBarStyle;
    }
  4. UITabbarController快速添加子控制器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    /**
    * 添加一个子控制器
    *
    * @param childVC 子控制器
    * @param title 标题
    * @param image 图片
    * @param selectedImage 选中的图片
    */
    - (void)addChildVc:(UIViewController *)childVC title:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectedImage
    {
    // 设置子控制器的文字
    childVC.title = title;
    // 设置子控制器的图片
    childVC.tabBarItem.image = [[UIImage imageNamed:image]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVC.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImage]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    // 设置文字的样式
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor itemColor];
    NSMutableDictionary *selectTextAttrs = [NSMutableDictionary dictionary];
    selectTextAttrs[NSForegroundColorAttributeName] = [UIColor themeColor];
    [childVC.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
    [childVC.tabBarItem setTitleTextAttributes:selectTextAttrs forState:UIControlStateSelected];
    // 添加为子控制器
    [self addChildViewController:childVC];
    }
  5. UINavigationController
    统一设置返回键样式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
    {
    if (self.viewControllers.count > 0) {
    // 自动显示和隐藏tabbar
    viewController.hidesBottomBarWhenPushed = YES;
    // 设置左边的返回按钮
    // UIBarButtonItem category 方法,快速修改图片
    viewController.navigationItem.leftBarButtonItem = [UIBarButtonItem
    itemWithTarget:self action:@selector(popVC) image:@"wihteback_normal"
    highImage:@"wihteback_hign"];
    }
    [super pushViewController:viewController animated:animated];
    }

    添加全屏返回手势

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    @property (nonatomic, strong) UIPanGestureRecognizer *pan; /**< 返回手势*/
    @property (nonatomic, assign) BOOL panGesEnable; /**< 是否启用全屏手势*/
    - (void)viewDidLoad
    {
    [super viewDidLoad];
    // 获取系统自带滑动手势的target对象
    id target = self.interactivePopGestureRecognizer.delegate;
    // 创建全屏滑动手势,调用系统自带滑动手势的target的action方法
    SEL action = NSSelectorFromString(@"handleNavigationTransition:");
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:target action:action];
    // 设置手势代理,拦截手势触发
    pan.delegate = self;
    self.pan = pan;
    // 给导航控制器的view添加全屏滑动手势
    [self.view addGestureRecognizer:pan];
    // 禁止使用系统自带的滑动手势
    self.interactivePopGestureRecognizer.enabled = NO;
    // 默认启用
    self.panGesEnable = YES;
    }
    - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
    {
    if (!self.panGesEnable) {
    return NO;
    }
    return self.childViewControllers.count == 1 ? NO : YES;
    }
  6. UIColor

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    // 使用16进制颜色
    + (UIColor *)colorWithRGBHex:(UInt32)hex
    {
    int r = (hex >> 16) & 0xFF;
    int g = (hex >> 8) & 0xFF;
    int b = (hex) & 0xFF;
    return [UIColor colorWithRed:r / 255.0f
    green:g / 255.0f
    blue:b / 255.0f
    alpha:1.0f];
    }
    // 使用16进制颜色字符串格式
    + (UIColor *)colorWithHexString:(NSString *)stringToConvert
    {
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
    return [UIColor clearColor];
    }
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
    cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
    cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
    return [UIColor clearColor];
    NSScanner *scanner = [NSScanner scannerWithString:cString];
    unsigned hexNum;
    if (![scanner scanHexInt:&hexNum]) return nil;
    return [UIColor colorWithRGBHex:hexNum];
    }
    // 常用颜色写成分类
    + (UIColor *)themeColor
    {
    return [UIColor colorWithRed:0 green:0 blue:0 alpha:1.0];
    }
  7. UIImage

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    // 根据颜色生成图片
    + (UIImage *)imageWithColor:(UIColor *)color
    {
    return [self imageWithColor:color size:CGSizeMake(1, 1)];
    }
    + (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
    {
    if (!color || size.width <= 0 || size.height <= 0) return nil;
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    }
  8. UIView && UIViewController
    为UIView快速添加边框
    UIView+Borders.h
    为UIView添加红点,数字等
    WZLBadge
    根据视图找到控制器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    - (UIViewController *)viewController
    {
    for (UIView *view = self; view; view = view.superview) {
    UIResponder *nextResponder = [view nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
    return (UIViewController *)nextResponder;
    }
    }
    return nil;
    }

    获取某个范围内的图形

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    - (UIImage *)imageFromView:(UIView *)theView atFrame:(CGRect)r
    UIGraphicsBeginImageContext(theView.frame.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSaveGState(context); 
    UIRectClip(r); 
    [theView.layer renderInContext:context]; 
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext();          
    return  theImage; 
    }

    UIView移除所有子视图

    1
    2
    3
    4
    5
    6
    - (void)removeAllSubviews
    {
    while (self.subviews.count) {
    [self.subviews.lastObject removeFromSuperview];
    }
    }

    UIViewController默认设置

    1
    2
    3
    4
    5
    6
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    - (UIEdgeInsets)contentInset
    {
    return UIEdgeInsetsMake(64, 0, 0, 0);
    }

    网易云音乐启动动画

    1
    2
    3
    4
    5
    6
    7
    TestViewController *test = [[TestViewController alloc] init];
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;   
    [UIView transitionWithView:keyWindow duration:0.5 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
            [UIApplication sharedApplication].keyWindow.rootViewController = test;
    } completion:^(BOOL finished) {
           
    }];
  9. UITableViewCell && UITableView && UITableViewController
    table view cell选中背景

    1
    2
    3
    4
    5
    6
    7
    8
    9
    - (void)setSelected:(BOOL)selected animated:(BOOL)animated
    {
    [super setSelected:selected animated:animated];
    if (selected) {
    // 选中
    } else {
    // 非选中
    }
    }

    table view cell 左右间距,不填充整个table view

    1
    2
    3
    4
    5
    6
    - (void)setFrame:(CGRect)frame
    {
    frame.origin.x = LEFT_MARGIN;
    frame.size.width = kScreenWidth - LEFT_MARGIN * 2;
    [super setFrame:frame];
    }

    table view cell 分割线

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // 方法1,重写drawRect方法
    - (void)drawRect:(CGRect)rect
    {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
        CGContextFillRect(context, rect);
       
        //上分割线
        CGContextSetStrokeColorWithColor(context,[UIColor whiteColor].CGColor);
        CGContextStrokeRect(context,CGRectMake(0,0,rect.size.width,1));
       
        //下分割线
        CGContextSetStrokeColorWithColor(context,[UIColor whiteColor].CGColor);
        CGContextStrokeRect(context,CGRectMake(0,rect.size.height-1,rect.size.width,1));
    }
    // 方法2,隐藏自带分割线,然后再content view的layer上添加1像素的layer

    table view 默认设置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // 背景色
    tableView.backgroundColor = [UIColor viewBackgroundColor];
    // 分割线样式去除
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 表尾去除
    tableView.tableFooterView = [UIView new];
    // 表头去除
    tableView.tableHeaderView = [UIView new];
    // 区头默认有10高度,设置0无效,可以设置为0.01

    table view controller 添加3D Touch

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    // 1.遵循代理`UIViewControllerPreviewingDelegate`
    // 2.注册cell
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    DHCell *cell = [DHCell cellWithTableView:tableView];
    // 注册
    [self registerForPreviewingWithDelegate:self sourceView:cell];
    return cell;
    }
    // 3.需要跳转的目标控制器
    - (UIViewController *)previewingContext:(id <UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
    {
    NSIndexPath *indexPath = [_tableView indexPathForCell:(UITableViewCell* )[previewingContext sourceView]];
    DestinationViewController *destinationVC = [[DestinationViewController alloc] init];
    UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:destinationVC];
    return navc;
    }
    - (void)previewingContext:(id <UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
    {
    [self showViewController:viewControllerToCommit.childViewControllers[0] sender:self];
    }
    // 4.目标控制的操作,写在目标控制器的实现里面
    - (NSArray<id<UIPreviewActionItem>> *)previewActionItems
    {
    UIPreviewAction * action1 = [UIPreviewAction actionWithTitle:@"操作1" style:UIPreviewActionStyleDefault handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
    DHLog(@"操作1");
    }];
    UIPreviewAction * action2 = [UIPreviewAction actionWithTitle:@"操作2" style:UIPreviewActionStyleSelected handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
    DHLog(@"操作2");
    }];
    UIPreviewAction * action3 = [UIPreviewAction actionWithTitle:@"操作3" style:UIPreviewActionStyleDestructive handler:^(UIPreviewAction * _Nonnull action, UIViewController * _Nonnull previewViewController) {
    DHLog(@"操作3");
    }];
    NSArray * actions = @[action1,action2,action3];
    return actions;
    }

    app 添加 Shortcuts

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    UIApplicationShortcutItem *addItem = [[UIApplicationShortcutItem alloc] initWithType:SHORTCUT_TYPE_ADD localizedTitle:@"添加" localizedSubtitle:nil icon: [UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeAdd]
    userInfo:@{@"infoKey": @"infoValue"}];
    [UIApplication sharedApplication].shortcutItems = @[addItem];
    return YES;
    }
    - (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void(^)(BOOL succeeded))completionHandler
    {
    if ([shortcutItem.type isEqualToString:SHORTCUT_TYPE_ADD]) {
    // do something
    }
    }
  10. UIFont
    添加自定义字体
    第一步,Info.plist添加Fonts provided by application array,item0key,value 为字体文件名称全写;
    第二步,打印所以字体,找到自定义字体所在family名称,根据名称找到具体字的名称;

    1
    2
    NSArray *familays = [UIFont familyNames];
    NAArray *names = [UIFont fontNamesForFamilyName:familyName];

    第三步,加载字体.

    1
    UIfont *customFont = [UIFont fontWithName:fontName size:fontSize];