Which is the best way to change the color/view of disclosure indicator accessory view in a table view cell in iOS?

前端 未结 12 1958
有刺的猬
有刺的猬 2020-12-04 10:26

I need to change the color of the disclosureIndicatorView accessory in a UITableViewCell. I think there are two ways to get this done, but I\'m not

12条回答
  •  伪装坚强ぢ
    2020-12-04 10:34

    Here is an implementation that works in iOS 8+. It does exactly what's asked for:
    change the color of the original Apple disclosure indicator to a custom color.
    Use it like this:

    #import "UITableViewCell+DisclosureIndicatorColor.h"
    // cell is a UITableViewCell
    cell.disclosureIndicatorColor = [UIColor redColor]; // custom color
    [cell updateDisclosureIndicatorColorToTintColor]; // or use global tint color
    

    UITableViewCell+DisclosureIndicatorColor.h

    @interface UITableViewCell (DisclosureIndicatorColor)
    @property (nonatomic, strong) UIColor *disclosureIndicatorColor;
    - (void)updateDisclosureIndicatorColorToTintColor;
    @end
    

    UITableViewCell+DisclosureIndicatorColor.m

    @implementation UITableViewCell (DisclosureIndicatorColor)
    
    - (void)updateDisclosureIndicatorColorToTintColor {
        [self setDisclosureIndicatorColor:self.window.tintColor];
    }
    
    - (void)setDisclosureIndicatorColor:(UIColor *)color {
        NSAssert(self.accessoryType == UITableViewCellAccessoryDisclosureIndicator,
            @"accessory type needs to be UITableViewCellAccessoryDisclosureIndicator");
    
        UIButton *arrowButton = [self arrowButton];
        UIImage *image = [arrowButton backgroundImageForState:UIControlStateNormal];
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        arrowButton.tintColor = color;
        [arrowButton setBackgroundImage:image forState:UIControlStateNormal];
    }
    
    - (UIColor *)disclosureIndicatorColor {
        NSAssert(self.accessoryType == UITableViewCellAccessoryDisclosureIndicator, 
            @"accessory type needs to be UITableViewCellAccessoryDisclosureIndicator");
    
        UIButton *arrowButton = [self arrowButton];
        return arrowButton.tintColor;
    }
    
    - (UIButton *)arrowButton {
        for (UIView *view in self.subviews)
            if ([view isKindOfClass:[UIButton class]])
                return (UIButton *)view;
        return nil;
    }
    
    @end
    

提交回复
热议问题