2015-04-07 7 views
0

У меня есть меньшая проблема с добавлением subview в tableView Cell.Изменение размера подзапроса динамически в ячейке tableview

I мой фон для ячейки является динамическим от процентного подсчета ..

enter image description here

Я получаю процент правильно, а фон я могу установить отлично, но когда я добавить новую запись .. все облажались

enter image description here

Новая запись я получаю совершенным, но клетки, которые до того, как оставаться неизменным, даже после того, как я изменить его размер.

магическая вещь, когда я остановить и построить его все совершенствовать свой путь ..

enter image description here

Пожалуйста, помогите мне ..

я использую следующий код для достижения этой цели ...

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
// Dequeue the cell. 
speedoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"speedoCell" forIndexPath:indexPath]; 
[cell setSelectionStyle:UITableViewCellSelectionStyleNone]; 

CGRect rect = cell.frame; 

NSLog(@"Cell width = %f",rect.size.width); 
float cell_width=rect.size.width; 
float per; 
float viewSize=0.0; 


if (self.recent_calls.count == 0) { 
    cell.title.text [email protected]"No records"; 
    cell.desc.text [email protected]""; 
} 

else{ 
    NSInteger indexOfFirstname = [self.dbManager.arrColumnNames indexOfObject:@"ex_category"]; 
    NSInteger indexOfSecondname = [self.dbManager.arrColumnNames indexOfObject:@"totle"]; 

    NSString *totle_cat=[NSString stringWithFormat:@"%@", [[self.recent_calls objectAtIndex:indexPath.row] objectAtIndex:indexOfSecondname]]; 

    int x=[totle_cat intValue]; 
    NSLog(@"%d--yoyoyoyoyoyoyoyoyoyo--%d",x,amount_totle); 

    float result=0; 

    result=((float)x/(float)amount_totle)*100; 

// cell_width is static = 343.0 ..... result is percentage we found 
viewSize=(cell_width*result)/100; 

    NSLog(@"%f----------",viewSize); 

    UIView *view,*view1; 


    view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)]; 
    view1=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)]; 


    view1.frame=CGRectMake(5, 5, cell.frame.size.width-10, cell.frame.size.height-3); 

    [view1.layer setCornerRadius:8.0f]; 
    [view1.layer setMasksToBounds:YES]; 
    [view1.layer setBorderWidth:0.5f ]; 


    CGRect frame = view.frame; 
    frame.size.width = viewSize; 
    frame.size.height=cell.frame.size.height-3; 
    view.frame = frame; 


    NSLog(@"%f",view.frame.size.width); 

    [view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"road_panorama1.jpg"]]]; 


    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; 

    UIVisualEffectView *visualEffectView; 
    visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect]; 

    visualEffectView.frame = CGRectMake(0, 0, viewSize, cell.frame.size.height-3); 
    [view addSubview:visualEffectView]; 

    [view1 setBackgroundColor:[UIColor whiteColor]]; 

    [view1 insertSubview:view atIndex:0]; 

    [cell.contentView insertSubview:view1 atIndex:0]; 
UIImage *image; 
    if ([category isEqualToString:@"Travel"]) { 
     image=[UIImage imageNamed:@"taxi13.png"]; 

    } 
    else if ([category isEqualToString:@"Food"]) { 

     image=[UIImage imageNamed:@"fastfood6.png"]; 
    } 
    else if ([category isEqualToString:@"Medical"]) { 

     image=[UIImage imageNamed:@"stethoscope11.png"]; 
    } 
    else if ([category isEqualToString:@"Shopping"]) { 

     image=[UIImage imageNamed:@"shopping-cart13.png"]; 
    } 
    else{ 


     image=[UIImage imageNamed:@"question-mark2.png"]; 
    } 


    [cell.img setImage:image]; 




} 
return cell; 

}

Добавление т он запись из второго вида контроллера

NSString *query= [NSString stringWithFormat:@"insert into ex_man_last (ex_title,ex_amount,ex_description,ex_date,ex_category,ex_upload_date,ex_image,ex_my) values ('%@','%@','%@','%@','%@','%@','%@','%@')",_ex_title.text,_ex_amount.text,_ex_description.text,_ex_date.text,_ex_category.text,datestring,imageName,my ]; 

// Execute the query. 
[self.dbManager executeQuery:query]; 

и вызова метода, чтобы получить обновленную запись из БД ввиду появится способ ..

NSString *query =[NSString stringWithFormat:@"SELECT *,sum(ex_amount) as totle FROM ex_man_last where ex_my='%@' GROUP BY ex_category ",query_date]; 


if (self.recent_calls != nil) { 
    self.recent_calls = nil; 

} 
self.recent_calls = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]]; 
NSLog(@"--->%@",_ex_main); 
NSLog(@"%lu",(unsigned long)[self.recent_calls count]); 

NSInteger indexOfSecondname = [self.dbManager.arrColumnNames indexOfObject:@"totle"]; 

for (int i=0; i<[self.recent_calls count]; i++) { 
    NSString *amount=[[self.recent_calls objectAtIndex:i] objectAtIndex:indexOfSecondname] ; 
    amount_totle=amount_totle+[amount intValue]; 
} 

Весь код находится в ячейке для строки в методе индекс пути. ..

Пожалуйста, помогите мне ... Спасибо заранее ...

+0

Для вашего рестарта он работает хорошо в том смысле, код в ячейке для строки правильно, как вы добавляете новую запись в виде таблицы вы убедитесь, что вы перезагружают таблицу. – MaheshBabu

+0

Вы не принимаете во внимание повторное использование ячеек. Когда вы прокручиваете, и ячейка повторно используется, вы будете добавлять view1 в ячейку, у которой уже есть view1. – rdelmar

+0

Вы можете опубликовать полную версию cellForRowAtIndexPath: и как добавить новую запись и перезагрузить таблицу? –

ответ

1

oky, позволяет попробовать это,

почему вы делаете все, что в методе cellForRowAtIndexPath его работа состоит в том, чтобы вернуть клетки для Tableview не обрабатывать все подвидов внутри клетки

клеток является который обрабатывает каждую вещь внутри нее. он содержит представление содержимого, которое содержит компоненты вашего представления, поэтому мы не разрешаем ячейке обрабатывать свои компоненты представления. Для этого нам нужно передать некоторую информацию к нему, например, в вашем случае процент и тексты ярлыков, а изображения, которые вы показываете, и оставить их в ячейке. Это будет использовать полнофункциональную функцию, также если u изменяет что-то или добавляет новые компоненты в соответствии с шаблоном (MVC).

Я не собираюсь делать все, просто фокусируясь на вашей проблеме, в вашем cellForRowAtIndexPath вы продолжаете добавлять новые представления каждый раз даже для повторно используемой ячейки. просто удалите весь код обработки вида (это будет использоваться в пользовательской ячейке)

Если вы хотите просто создать новый проект и попробовать его, я действительно пробовал ваш код здесь, и я отлично работаю, поэтому давайте попробуем попробовать это новый проект, так что вы четко понимаете, и в конце я также добавлю gif-файл, чтобы показать, как результат.

сначала создать новый файл с подклассу UITableViewCell и дать ему имя, я отдаю в CustomCell

в CustomCell.h файле

#import <UIKit/UIKit.h> 
#import <QuartzCore/QuartzCore.h> 

@interface CustomCell : UITableViewCell 

//creating the properties for all view components and also for percentage value that we need for calculating of width 
//i took your code hear 
@property (nonatomic, assign) CGFloat percentage; 
@property (nonatomic, assign) CGFloat viewWidth; 

@property (nonatomic, strong) UIView *view; 
@property (nonatomic, strong) UIView *view1; 

@property (nonatomic, strong) UIBlurEffect *blurEffect ; 

@property (nonatomic, strong) UIVisualEffectView *visualEffectView; 
@property (nonatomic, strong) UILabel *percentageLabel ; 
@end 

в CustomCell.m файле

#import "CustomCell.h" 

@implementation CustomCell 

//we are using this to create new cell just override it and call super 
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
    { 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if(self) 
    { 
     [self initiliseViewComponents]; //hear we are adding views to cell 
    } 
    return self; 
} 

- (void)setPercentage:(CGFloat)percentage 
{ 
    float result=0; 
    result=((float)percentage/(float)100)*100; 
    _percentage = result; 
    _viewWidth = result*343/100; 
    _percentageLabel.text = [NSString stringWithFormat:@"%d",(int)_percentage]; //to show the percentage 
} 

//at this point we don't no the size of cell, 
//same what u are doing in your project just initialising and add it to cell's content view 
- (void)initiliseViewComponents 
{ 
    _view    = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)]; 
    _view1   = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)]; 

_blurEffect  = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; 
_visualEffectView = [[UIVisualEffectView alloc] initWithEffect:_blurEffect]; 

_percentageLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)]; 


[_view addSubview:_visualEffectView]; 
[_view1 setBackgroundColor:[UIColor whiteColor]]; 

[_view1 insertSubview:_view atIndex:0]; 
[self.contentView insertSubview:_view1 atIndex:0]; 
[self.contentView addSubview:_percentageLabel]; 
} 

- (void)awakeFromNib { 
// Initialization code 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated { 
    [super setSelected:selected animated:animated]; 
    // Configure the view for the selected state 
} 

//in this method just set frames for your subviews this method will be called automatically 
//dont change the cell's frame just the subviews frame 

- (void)layoutSubviews 
{ 
    _percentageLabel.frame = CGRectMake(self.contentView.bounds.size.width - 50, self.contentView.bounds.origin.y + 10, 50, 50); 

    CGRect cellFrame = self.contentView.frame; 
    cellFrame.origin.x += 5; 
    cellFrame.origin.y += 5; 
    cellFrame.size.width -= 10; 
    cellFrame.size.height -= 3; 
    _view1.frame=cellFrame; 

    [_view1.layer setCornerRadius:8.0f]; 
    [_view1.layer setMasksToBounds:YES]; 
    [_view1.layer setBorderWidth:0.5f ]; 

    // [_view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"images2.jpg"]]]; 
    [_view setBackgroundColor:[UIColor redColor]]; 
    self.backgroundColor = [UIColor clearColor]; 

    CGRect frame  = _view.frame; 
    frame.size.width = _viewWidth; 
    frame.size.height = self.frame.size.height-3; 
    _view.frame = frame; 
    _visualEffectView.frame = CGRectMake(0, 0, _viewWidth, frame.size.height); 
    NSLog(@"%f",_view.frame.size.width); 

    [super layoutSubviews]; //finally call super 
} 

@end 

и прийти на главный контроллер в главном контроллере, добавить TableView и кюретки выходное отверстие для его

//in ViewController.h 
@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> 
@property (weak, nonatomic) IBOutlet UITableView *aTableView; 
@property (strong,nonatomic) NSMutableArray *aMutableArray; //to holde percentages 

в ViewController.m реализации источника данных и делегатов

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    _aMutableArray = [[NSMutableArray alloc]initWithObjects:@(20),@(30),@(50), nil]; //initially it has 3 values we will add some more dynamically 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return _aMutableArray.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"]; 
    if(cell == nil) 
    { 
     cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"]; 
    } 
    cell.percentage = [[_aMutableArray objectAtIndex:indexPath.row] floatValue]; 
    return cell; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return 60.0f; 
} 

//this action method to add new cell dynamically at the top of the tableview 
- (IBAction)addButtonAction:(id)sender 
{ 
    CGFloat nextPerent = arc4random_uniform(80) % 100; //i took some random percentage values 
    [_aMutableArray insertObject:[NSNumber numberWithFloat:nextPerent] atIndex:0]; 
    [_aTableView reloadData]; 
} 

так ударил кнопку запуска и результат будет, как показано ниже

enter image description here

жаль для gif-изображения, которое я должен был сжать, качество немного низкое. Кнопка с синим цветом заключается в добавлении новой ячейки в tableview, а l Авель не требуется

надеюсь, что это помогает U

1

Как вы используете многоразовые ячейку с помощью speedoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"speedoCell" forIndexPath:indexPath];

поэтому, как только ячейка будет выделена, она будет повторно использована снова и снова.

Рассмотрите случай, в первый раз вы создаете таблицу с двумя ячейками, как показано на снимке экрана 1, с медицинским и путешествованием, имеющим 80 & 20% соответственно соответственно, вы создали размытие и добавили его на белый вид, наконец, вы вставили view1 (просмотр с белым фоном, содержащим эффект размытия) над 0-м индексом contentView ячейки.

Вышеупомянутый случай работает отлично.

Опять же, вы вставляете новую запись (ячейку). Еда, все перепутано !!! Проблема заключается в том, что, поскольку две ячейки были созданы ранее для индексов 0 и 1, поэтому они были повторно использованы, на этот раз данные были изменены и, соответственно, вы рассчитали размытие и белую область, создали представление и снова вставили содержимое contentView ячейки по индексу 0 , вот в чем проблема.

Вид, уже вставленный в индекс, будет виден независимо от других представлений, добавленных по тому же индексу над надстройкой.

Чтобы решить эту проблему, если ячейка повторно, чем сначала вы должны проверить, если повторная ячейка содержит белый фон вид с эффектом размытия, то вы должны удалить его первым, пересчитывать размытость и белую область и снова вставьте view1 в индекс 0 содержимого contentView.

Это время, когда ячейка была повторно использована, поэтому сначала мы удаляем уже вставленный вид с индексом 0 из представления содержимого ячейки, снова создаем вид белого + размытия и вставляем вновь созданный вид на 0-й индекс ячейки просмотр содержимого, и всегда будет отображаться вновь созданный (как в тот момент, когда один будет существовать, а затем удален).

+0

Как это сделать? ? –

+0

Спасибо, позвольте мне попробовать –

+0

просто назначить тег view1 перед тем, как вставить его в представление содержимого ячейки как [view1 setTag: VIEW_TAG]; –

Смежные вопросы