首页 > 代码库 > 关于UIScrollView有些你很难知晓的崩溃情形

关于UIScrollView有些你很难知晓的崩溃情形

关于UIScrollView有些你很难知晓的崩溃情形

为了实现以下的功能(按钮之间的切换效果):

简短的代码如下:

////  RootViewController.m//  BUG////  Copyright (c) 2014年 Y.X. All rights reserved.//#import "RootViewController.h"@interface RootViewController (){    UIView    *_showView;}@end@implementation RootViewController- (void)viewDidLoad{    [super viewDidLoad];    _showView = [[UIView alloc] initWithFrame:self.view.bounds];    [self.view addSubview:_showView];        NSArray *title = @[@"YouXianMing",                       @"XianHui",                       @"XianMing",                       @"XianNeng",                       @"XianRen"];        [title enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {        // 初始化button        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(50, 50*(idx + 1), 130, 30)];        button.layer.borderWidth = 1.f;        [_showView addSubview:button];                // 设置字体        button.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-Thin"                                                 size:15.f];                // 设置标题以及标题颜色        [button setTitle:obj                forState:UIControlStateNormal];        [button setTitleColor:[UIColor redColor]                     forState:UIControlStateNormal];                // 添加事件        [button addTarget:self                   action:@selector(buttonsEvent:)         forControlEvents:UIControlEventTouchUpInside];    }];}- (void)buttonsEvent:(UIButton *)button{    [_showView.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {        UIButton *tmpButton = obj;                if ([tmpButton isEqual:button])        {            [tmpButton setTitleColor:[UIColor redColor]                            forState:UIControlStateNormal];        }        else        {            [tmpButton setTitleColor:[UIColor blackColor]                            forState:UIControlStateNormal];        }    }];}@end

之后,将UIView替换成UIScrollView后:

然后就会崩溃-_-!!

崩溃信息:

*** Terminating app due to uncaught exception ‘NSInvalidArgumentException‘, reason: ‘-[UIImageView setTitleColor:forState:]: unrecognized selector sent to instance 0xa590390‘

崩溃原因是_showView.subviews里面有一个UIImageView

我们并没有添加这个东西UIImageView到subviews中呢,其实,这个东西是UIScrollView自己的一个东西......

写上以下保护性语句就没问题了.

话说,UIScrollView跟你偷偷加了点东西让你崩溃了都不知道咋回事-_-!!!