点击UITableViewCell发生了什么?

EstWheatley 7年前
   <p>今天遇到一个有关 UITableViewCell 的奇怪现象。</p>    <p>我的 UITableViewCell 上有一个 subview ,是用来显示未读数的。我给这个 subview 设置了一个红色背景,就像这样:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/7835a5b50a0e8984ecc38be0f21b95e1.png"></p>    <p style="text-align: center;">未选择cell时</p>    <p>但是我选中这个cell时,发现未读数的背景色没有了,只有数字,就像这样:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/1a597b7afc54e5168742ea210c827811.png"></p>    <p style="text-align: center;">选择cell时</p>    <p>借此机会我了解到我们通常点击一个 UITableViewCell 时发生了哪些事,我按照调用方法的顺序绘制了一个简单的流程图:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/68e9b2268ea46b41dc2690a02e968f09.png"></p>    <p style="text-align: center;">点击UITableViewCell的调用方法</p>    <p>可以看到,手指按下的时候,Cell就进入 highlighted 状态。其实,Cell的 subview 也同时进入了 highlighted 状态。这个时候,Cell会把所有所有 subview 的背景色清空,以便设置统一的背景色。一般有如下几种选中模式:</p>    <p>UITableViewCellSelectionStyleNone,</p>    <p>UITableViewCellSelectionStyleBlue,</p>    <p>UITableViewCellSelectionStyleGray,</p>    <p>UITableViewCellSelectionStyleDefault</p>    <h3>解决办法</h3>    <p>我们可以选择UITableViewCellSelectionStyleNone,背景色就不会修改的。但是显然不能满足我们的应用场景。</p>    <p>正如Apple开发文档说的:</p>    <p>A custom table cell may override this method to make any transitory appearance changes.</p>    <p>我们重载 (void)setSelected:(BOOL)selected animated:(BOOL)animated 和 (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated 方法,在这里面我们来设置 subview 的背景色。</p>    <pre>  <code class="language-objectivec">- (void)setSelected:(BOOL)selected animated:(BOOL)animated {        [super setSelected:selected animated:animated];      _unreadBadge.backgroundColor = [UIColor redColor];  }    - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {        [super setHighlighted:highlighted animated:animated];      _unreadBadge.backgroundColor = [UIColor redColor];  }</code></pre>    <p>这样既可以按照系统的选择风格来,又可以自定义 subview 背景色,perfect!</p>    <p> </p>    <p>来自:http://www.jianshu.com/p/903ef14f269b</p>    <p> </p>