iOS11 table左滑按钮自定义

1.UITableView视图层级

iOS8-10 :左滑视图层是UITableViewCell的子视图,UITableView -> UITableViewCell -> UITableViewCellDeleteConfirmationView -> _UITableViewCellActionButton;
iOS11中左滑视图层是UITableView的子视图,UITableView -> UISwipeActionPullView -> UISwipeActionStandardButton;

2.关于左滑按钮的自定义

iOS8-10之前: 则通过创建类继承UITableViewCell,然后该类中-(void)layoutSubviews来实现的;

  • (void)layoutSubviews{
    [super layoutSubviews];
    //遍历子视图,找出左滑按钮
    for (UIView *subView in self.subviews)
    {
    if([subView isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")])
    {
    for (UIButton *btn in subView.subviews) {
    if ([btn isKindOfClass:[UIButton class]]) {
    //更改左滑按钮样式自定义
    }
    }
    }
    }
    }

iOS11 : 由于视图层级发生变化,左滑视图被放到了UITableView上,则需要遍历UITableView的子视图拿到选项按钮在进行自定义;

目前我个人则采用创建类继承UITableView,并实现:

- (void)layoutSubviews
{
    [super layoutSubviews];
    [self customLeftSlideButtons];
}
- (void)customLeftSlideButtons
{
    // 获取选项按钮的reference
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"11.0"))
    {
        for (UIView *subview in self.subviews)
        {
            if ([subview isKindOfClass:NSClassFromString(@"UISwipeActionPullView")] && [subview.subviews count] >= 1)
            {
                subview.backgroundColor = kColor_White;
                for (UIButton *btn in subview.subviews) {
                    if ([btn isKindOfClass:[UIButton class]]) {
                        //更改左滑按钮样式
                        btn.titleLabel.font = kFont_System_13; //字体设置
                        [btn setTitleColor:kColor_White forState:UIControlStateNormal];
                        [btn setImage:[UIImage imageNamed:@"icon_star"] forState:UIControlStateNormal]; 
                            [btn setBackgroundColor:kColor_LableColor];
                        [self customCenterImageTitleBtn:btn]; //设置图片,文字上下居中模式
                    }
                }
            }
        }
    }
}
- (void) customCenterImageTitleBtn:(UIButton*)button
{
    CGFloat spacing = 10.0; //文字图片上下间距
    CGSize imageSize = button.imageView.image.size;
    CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: button.titleLabel.font}];
    CGFloat  allHeight = imageSize.height+spacing+titleSize.height;
    CGRect imageRect = button.imageView.frame;
    imageRect.origin.y = (CGRectGetHeight(button.frame)-allHeight)/2;
    button.imageView.frame = imageRect;
    
    CGRect  titleRect = button.titleLabel.frame;
    titleRect.origin.y = imageRect.origin.y+spacing+CGRectGetHeight(button.imageView.frame);
    button.titleLabel.frame = titleRect;
}
//   ---- 上述设置btn上文字图片上下格式时,也可以采用button.titleEdgeInsets,button.imageEdgeInsets进行设置;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容