简体   繁体   English

通过dequeueReusableCellWithIdentifier重用时,UITableViewCell中的UISegmentedControl会更改段索引顺序

[英]UISegmentedControl in UITableViewCell changing segment index order when reused through dequeueReusableCellWithIdentifier

I've got a UITableView with custom UITableCells. 我有一个带有自定义UITableCells的UITableView。 Inside those UITableCells are UISegmentedControls. 在这些UITableCells内部是UISegmentedControls。 I'm trying to change the tint color of just the first UISegment. 我正在尝试仅更改第一个UISegment的颜色。 This works correctly until the UITableCell is reused through dequeueReusableCellWithIdentifier. 在通过dequeueReusableCellWithIdentifier重用UITableCell之前,此方法可以正常工作。 When reused UITableCells begin to appear when scrolling down, the last segment is tinted blue rather than the first. 当向下滚动时开始出现可重复使用的UITableCells时,最后一个分段为蓝色而不是第一个分段。 Here is the relevant code in cellforRowAtIndexPath: 这是cellforRowAtIndexPath中的相关代码:

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    CellIdentifier = @"CustomCell";
    CustomTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
         cell = [[CustomTableCell alloc] init];
    }

    [cell.segmentedControl setTintColor:GRAY_COLOR];
    [[[cell.segmentedControl subviews] objectAtIndex:0] setTintColor:BLUE_COLOR];

    ...

    return (UITableViewCell *) cell;
}

This UISegmentedControl's UISegmentedControlStyle is UISegmentedControlStyleBar, if that matters. 如果需要的话,此UISegmentedControl的UISegmentedControlStyle为UISegmentedControlStyleBar。

You are digging into the undocumented subview structure of a segmented control. 您正在研究分段控件的未记录子视图结构。 There is no public API to tint one segment as you are. 没有公共API可以像您一样着色一个细分。 What happens when the implementation changes in the future and the subview you are getting doesn't respond to the 'setTintColor:' method? 当将来的实现发生更改并且您获得的子视图不响应“ setTintColor:”方法时,会发生什么?

You are also relying on the order of the subviews. 您还依赖于子视图的顺序。 The order can change. 顺序可以更改。 The implementation of the segmented control can move subviews to the back or front over time. 分段控件的实现可以将子视图随时间推移移到后部或前部。 You can't assume that subview 0 is the view for the first segment. 您不能假定子视图0是第一段的视图。

Your best approach here is to subclass UISegmentedControl or create your own custom control that properly make a segment a specific color. 此处最好的方法是将UISegmentedControl子类化或创建自己的自定义控件,以正确地将细分变成特定的颜色。

您可能会尝试在CustomTableCell类中实现prepareForReuse方法,以重置子视图,因为此消息在出队以在UITableView重用时将被发送到UITableViewCell (或子类)实例。

尝试在dequeueReusableCellWithIdentifier行之后使用[cell.segmentedControl setTintColor:[UIColor clearColor]];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM