Как сделать UITableViewRowAction полностью прозрачным в UitableView в Objective-C

Я хочу сделать UITableViewRowAction прозрачным, и мой фоновый вид должен быть виден при смахивании моего UITableViewCell влево в Objective-C. Я удалил все цвета фона, но фон все еще остается светло-серым.

Вот мой код:

ViewController.h

#import <UIKit/UIKit.h>


    @interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
    
    
    
    @property (nonatomic, strong) UITableView *MyCustomTableView;
    @property (nonatomic, strong)NSArray *MyTableViewData;
    @property (nonatomic, strong)UIImage *MyAppIconImage;
    @end

ViewController.m

#import "ViewController.h"
#import "MyTableViewCell.h"

static NSString *myCellID = @"myCellIdentifier";
@interface ViewController ()

@end

@implementation ViewController

@synthesize MyCustomTableView, MyTableViewData, MyAppIconImage;
- (void)viewDidLoad {
    [super viewDidLoad];
    UIGraphicsBeginImageContext(self.view.frame.size);
    [[UIImage imageNamed:@"SampleBg"] drawInRect:self.view.bounds];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.view.backgroundColor = [UIColor colorWithPatternImage:image];

    self.MyTableViewData = @[@{@"Title" : @"My TableView Title 1", @"Description" : @"My TableView Description 1"}, @{@"Title" : @"My TableView Title 2", @"Description" : @"My TableView Description 2"}, @{@"Title" : @"My TableView Title 3", @"Description" : @"My TableView Description 3"}, @{@"Title" : @"My TableView Title 4", @"Description" : @"My TableView Description 4"}, @{@"Title" : @"My TableView Title 5", @"Description" : @"My TableView Description 5"}, @{@"Title" : @"My TableView Title 6", @"Description" : @"My TableView Description 6"}, @{@"Title" : @"My TableView Title 7", @"Description" : @"My TableView Description 7"}, @{@"Title" : @"My TableView Title 8", @"Description" : @"My TableView Description 8"}];
    
    
    
UIImage *AppIconAsset = [UIImage imageNamed: [[NSBundle mainBundle].infoDictionary[@"CFBundleIcons"][@"CFBundlePrimaryIcon"][@"CFBundleIconFiles"] lastObject]];
    self.MyAppIconImage = [self ResizeImage: AppIconAsset scaledToSize: CGSizeMake(36, 36)];
    
    self.MyCustomTableView = [UITableView new];
    self.MyCustomTableView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview: self.MyCustomTableView];
    self.MyCustomTableView.dataSource = self;
    self.MyCustomTableView.delegate = self;
    [self.view addConstraints: [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[MyCustomTableView]|" options: 0 metrics: nil views: @{@"MyCustomTableView" : self.MyCustomTableView}]];
    
    [self.view addConstraints: [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[MyCustomTableView]|" options: 0 metrics: nil views: @{@"MyCustomTableView" : self.MyCustomTableView}]];
    MyCustomTableView.backgroundColor = [UIColor clearColor];
    
    [self.MyCustomTableView registerClass: [MyTableViewCell class].self forCellReuseIdentifier: myCellID];
    self.MyCustomTableView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0);
    self.MyCustomTableView.allowsMultipleSelectionDuringEditing = NO;
    self.MyCustomTableView.alwaysBounceVertical = NO;
    [self.MyCustomTableView setShowsHorizontalScrollIndicator:NO];
    [self.MyCustomTableView setShowsVerticalScrollIndicator:NO];
    [self.MyCustomTableView setContentOffset: self.MyCustomTableView.contentOffset animated: NO];
    self.MyCustomTableView.estimatedRowHeight = 44;
    self.MyCustomTableView.backgroundView = nil;
   // self.MyCustomTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.MyCustomTableView setSeparatorColor:[UIColor blackColor]];
    self.MyCustomTableView.tableFooterView = [[UIView alloc] initWithFrame: CGRectZero];
    [self.MyCustomTableView.inputAccessoryView setBackgroundColor:[UIColor clearColor]];
    self.MyCustomTableView.opaque = NO;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  [self.MyTableViewData count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MyTableViewCell *myCell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier: myCellID forIndexPath: indexPath];
    if (myCell == nil) {
        myCell = [[MyTableViewCell alloc] initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier: myCellID];
    }
    
    myCell.MyCellImageView = [UIImageView new];
    myCell.MyCellImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [myCell.contentView addSubview: myCell.MyCellImageView];
    [myCell.contentView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"H:|-12-[MyCellImageView(34)]" options: 0 metrics: nil views: @{@"MyCellImageView": myCell.MyCellImageView}]];
    [myCell.contentView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"V:|-5-[MyCellImageView(34)]" options: 0 metrics: nil views: @{@"MyCellImageView": myCell.MyCellImageView}]];
    
   
    
    
    myCell.MyCellImageView.image = self.MyAppIconImage;
    myCell.MyCellImageView.backgroundColor = [UIColor clearColor];

    myCell.MyCellImageView.contentMode = UIViewContentModeCenter;
    myCell.MyCellImageView.userInteractionEnabled = NO;
    myCell.MyCellImageView.clipsToBounds = YES;
    myCell.MyCellImageView.layer.cornerRadius = 17;
    
    
    myCell.MyCellTitleLabel = [UILabel new];
    myCell.MyCellDescriptionLabel = [UILabel new];
    myCell.MyCellTitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    myCell.MyCellDescriptionLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    [myCell.contentView addSubview: myCell.MyCellTitleLabel];
    [myCell.contentView addSubview: myCell.MyCellDescriptionLabel];
    
    [myCell.contentView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"H:[MyCellImageView]-10-[MyCellTitleLabel]-10-|" options: 0 metrics: nil views: @{@"MyCellTitleLabel" : myCell.MyCellTitleLabel, @"MyCellImageView": myCell.MyCellImageView}]];
    [myCell.contentView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"H:[MyCellImageView]-10-[MyCellDescriptionLabel]-10-|" options: 0 metrics: nil views: @{@"MyCellDescriptionLabel" : myCell.MyCellDescriptionLabel, @"MyCellImageView": myCell.MyCellImageView}]];
    [myCell.contentView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"V:|-10-[MyCellTitleLabel]" options: 0 metrics: nil views: @{@"MyCellTitleLabel" : myCell.MyCellTitleLabel}]];
    
    [myCell.contentView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"V:[MyCellTitleLabel]-(5)-[MyCellDescriptionLabel]-10-|" options: 0 metrics: nil views: @{@"MyCellTitleLabel" : myCell.MyCellTitleLabel, @"MyCellDescriptionLabel" : myCell.MyCellDescriptionLabel}]];
    
    
     myCell.MyCellTitleLabel.text = [[self.MyTableViewData objectAtIndex:indexPath.row] valueForKey: @"Title"];
    
    myCell.MyCellDescriptionLabel.text = [[self.MyTableViewData objectAtIndex:indexPath.row] valueForKey: @"Description"];
    myCell.MyCellDescriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
    myCell.MyCellDescriptionLabel.numberOfLines = 0;
    
    myCell.MyCellDescriptionLabel.textAlignment = NSTextAlignmentJustified;
    myCell.MyCellDescriptionLabel.backgroundColor = [UIColor clearColor];
    
    myCell.backgroundColor = [UIColor clearColor];
    myCell.backgroundView.backgroundColor = [UIColor clearColor];
    myCell.backgroundView.opaque = NO;
    myCell.backgroundView = nil;
    myCell.textLabel.textColor = [UIColor blackColor];
    return myCell;
}



- (NSArray<UITableViewRowAction *> *)tableView: (UITableView *)tableView editActionsForRowAtIndexPath: (NSIndexPath *)indexPath
{
    MyTableViewCell *myCell = [MyCustomTableView cellForRowAtIndexPath: indexPath];
    [myCell.contentView layoutIfNeeded];
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title: @"Delete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        NSLog(@"rowAction Performed !!");
    }];
    rowAction.backgroundColor = [UIColor clearColor];
    return @[rowAction];
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //  [self.objects removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation: UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}


-(UIImage*)ResizeImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

MyTableViewCell.h

#import <UIKit/UIKit.h>

@interface MyTableViewCell : UITableViewCell
@property (nonatomic, strong) UILabel *MyCellTitleLabel;
@property (nonatomic, strong)UILabel *MyCellDescriptionLabel;
@property (nonatomic, strong)UIImageView *MyCellImageView;

@end

MyTableViewCell.m

#import "MyTableViewCell.h"

@implementation MyTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

-(id)initWithStyle: (UITableViewCellStyle)style reuseIdentifier: (NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier: reuseIdentifier];
    if (self) {
        self.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        
        
        //    self.nvFullScrnPlayerDelegate = self;
    }
    return self;
}

- (void)prepareForReuse {
    [super prepareForReuse];
    
    for(UIView *subview in [self.contentView subviews]) {
        [subview removeFromSuperview];
    }
}

-(void)layoutSubviews {
    [super layoutSubviews];
//    for (UIView *subview in  self.subviews) {
//        for (UIView *subview2 in subview.subviews) {
//
////NSRange range = ;
//            if ([(NSString *)subview2 rangeOfString:@"UITableViewCellActionButton"].location != NSNotFound) {
//                NSLog(@"1234567890");
//            }
////            if (range.location != NSNotFound) {
////                for (UIView *view in  subview2.subviews) {
////
////NSRange newRange = [(NSString *)view rangeOfString: @"UIButtonLabel"];
//////     if (String(view).rangeOfString("UIButtonLabel") != nil) {
////if (newRange.location != NSNotFound) {
////    UILabel *Textlabel = (UILabel *)view;
////    if (Textlabel == (UILabel *) view) {
////        Textlabel.textColor = [UIColor blackColor];
////    }
////                    }
////                }
////            }
//
//        }
//    }      

}
@end

И вот мой Результат:

Как сделать UITableViewRowAction полностью прозрачным в UitableView в Objective-C

При повторном прокрутке в той же ячейке tableview я получаю ожидаемый результат, но не при первом прокрутке.

Может ли кто-нибудь помочь мне решить эту проблему?

Попробуйте этот способ В editActionsForRowAtIndexPath MyTableViewCell * myCell = (MyTableViewCell *) [tableView cellForRowAtIndexPath: indexPath]; и rowAction.backgroundColor = [UIColor clearColor]; Для справки: - qaru.site/questions/94631/…

Rajesh Dharani 18.09.2018 05:55

В cellForRowAtIndexPath добавьте тег для каждой ячейки, например myCell.tag = indexPath.row;

Rajesh Dharani 18.09.2018 06:05

Тот же серый фон не удаляется при смахивании. Я хочу навсегда удалить светло-серый фон, проведя пальцем по ячейке для удаления.

Mohammad Ashraf Ali 18.09.2018 13:05
Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
3
234
2

Ответы 2

Надеюсь, это вам поможет!

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath  
{  
    UITableViewRowAction *callAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {  

        NSLog(@"View Action fired");  
    }];  
    callAction.backgroundColor = [UIColor clearColor];  

    return @[callAction];  
}

Попробуйте @MohammadAshrafAli и дайте мне знать!

Vicky_Vignesh 19.09.2018 11:39

Как я проверил еще раз, это нормально работает в iOS 10, но серый фон появляется на устройстве iOS 11 или более поздней версии. И скриншот iPhoneX Simulator прилагается.

Mohammad Ashraf Ali 20.09.2018 10:12

Если вы установите четкий цвет, это означает, что он показывает светло-серый цвет. Вместо чистого цвета вы можете установить изображение SampleBg. Из изображения вы можете получить тот же цвет фона в табличном представлении. Попробуйте код ниже. Он будет работать.

- (NSArray<UITableViewRowAction *> *)tableView: (UITableView *)tableView editActionsForRowAtIndexPath: (NSIndexPath *)indexPath
{

    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"Delete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {

        NSLog(@"rowAction Performed !!");
    }];
    UIGraphicsBeginImageContext(self.view.frame.size);
    [[UIImage imageNamed:@"SampleBg"] drawInRect:self.view.bounds];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    rowAction.backgroundColor = [UIColor colorWithPatternImage:image];
    return @[rowAction];
}

Привет, Раджеш, он рисует изображение основного вида из его верхнего левого угла, поэтому изображение выглядит как другое изображение из-за цвета градиента в основном изображении

Mohammad Ashraf Ali 21.09.2018 15:18

Другие вопросы по теме