UITableView刪除按鈕iOS10適配

在開發中,經常會遇到修改tableView的刪除按鈕的情況;默認情況下,當系統語言是中文時,刪除按鈕顯示【刪除】,英文時,顯示爲【del】

iOS9及之前

刪除按鈕是cell的子視圖,所以我們只需要在定製cell的時候,重寫layout方法,遍歷所有子視圖找到刪除按鈕修改即可,如下:

- (void)layoutSubviews {
[super layoutSubviews];
for (UIView *subView in self.subviews){
    if([subView isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")]) {
        CGRect cRect = subView.frame;
        cRect.origin.y = 11;
        cRect.size.height = self.contentView.frame.size.height - 11;
        subView.frame = cRect;

        UIView *confirmView=(UIView *)[subView.subviews firstObject];
        // 改背景顏色
        confirmView.backgroundColor = [CMBUITheme themePromotionColor];
        for(UIView *sub in confirmView.subviews){
            if([sub isKindOfClass:NSClassFromString(@"UIButtonLabel")]){
                UILabel *deleteLabel=(UILabel *)sub;
                // 改刪除按鈕的字體
                deleteLabel.font = [UIFont boldSystemFontOfSize:12.0];
                // 改刪除按鈕的文字
                deleteLabel.text = @"刪除";
                deleteLabel.textColor = [CMBUITheme themeSecondaryColor];
            }
        }
        break;
    }
}
}

iOS10

但是iOS10中,刪除按鈕不再屬於cell,而是直屬於tableview,和cell是並列的關係;所以當我們採用上面的方法是無法找到的,但是可以採用同樣的思路,遍歷tableView的子視圖即可;工作中一個示例:

- (void)layoutSubviews {
[super layoutSubviews];
for (UIView *subView in self.subviews) {
    if ([subView isKindOfClass:NSClassFromString(@"UISwipeActionPullView")]) {
        subView.backgroundColor = [CMBUITheme themePageBackgroundColor];
        for (UIView *view in subView.subviews) {
            if ([view isKindOfClass:[UIButton class]]) {
                UIButton *btn = (UIButton *)view;
                CGRect cRect = btn.frame;
                cRect.origin.y = 11;
                cRect.size.height = subView.frame.size.height - 11;
                btn.frame = cRect;
                // 改刪除按鈕的字體
                btn.titleLabel.font = [UIFont boldSystemFontOfSize:12.0];
                // 改刪除按鈕的文字
                [btn setTitle:@"刪除" forState:UIControlStateNormal];
                [btn setTitleColor:[CMBUITheme themeSecondaryColor] forState:UIControlStateNormal];
            }
        }
    }
}
}

自定義一個tableview繼承於UITableview,之後使用自定義的視圖即可;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章