2013-04-08 4 views
0

Мне нужно создать табличное представление с одной ячейкой, имеющей scrollview с поддержкой пейджинга и пейджинга. Я уже пробовал следовать.ScrollView с пейджингом в ячейке TableView

Я создал ячейку Tableview в IB, которая имеет две вещей в нем 1.ScrollView 2.Page управления и некоторые знаки, наносимые во время выполнения на каждой странице Scrollview, я испытали это Scrollview и пейджинг управление в обычном режиме просмотра и он работает так, как ожидалось.

У меня следующий код в ScrollViewCell.h

#import <UIKit/UIKit.h> 

@interface ScrollViewCell : UITableViewCell<UIScrollViewDelegate> 
{ 
UIPageControl* pageControl; 
UIScrollView* scrollView; 
BOOL pageControlBeingUsed; 
} 

@property (nonatomic, retain) IBOutlet UIScrollView* scrollView; 
@property (nonatomic, retain) IBOutlet UIPageControl* pageControl; 
- (IBAction)changePage; 

@end 

И следующий код в ScrollViewCell.m

#import "ScrollViewCell.h" 

@implementation ScrollViewCell 

@synthesize scrollView; 
@synthesize pageControl; 


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString*)reuseIdentifier 
{ 
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
if (self) { 
    // Initialization code 
    NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil]; 
    for (int i = 0; i < colors.count; i++) { 
     CGRect frame; 
     frame.origin.x = self.scrollView.frame.size.width * i; 
     frame.origin.y = 0; 
     frame.size = self.scrollView.frame.size; 

     UIView *subview = [[UIView alloc] initWithFrame:frame]; 
     subview.backgroundColor = [UIColor grayColor]; 

     [self.scrollView addSubview:subview]; 

     // add buttons 
     CGRect Frame= CGRectMake(frame.origin.x,frame.origin.y,200,50); 
     //set your x and y position whatever u want. 

     UIButton *Button = [UIButton buttonWithType:UIButtonTypeCustom]; 
     Button.frame = Frame; 

     UIImage *Img = [UIImage imageNamed:@"second.png"]; 
     [Button setBackgroundImage:Img forState:UIControlStateNormal]; 

     [scrollView addSubview: Button]; 

     // add text 
     UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(frame.origin.x,frame.origin.y+60,200,50)]; 
     label.textAlignment = UITextAlignmentCenter; 
     label.text = @"Here you write your text"; 
     label.textColor = [UIColor blackColor]; 

     [scrollView addSubview:label ]; 
     [subview release]; 
    } 

    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height); 


} 
return self; 
} 
- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{ 
[super setSelected:selected animated:animated]; 

// Configure the view for the selected state 
} 

- (void)scrollViewDidScroll:(UIScrollView *)sender { 
if (!pageControlBeingUsed) { 
    // Switch the indicator when more than 50% of the previous/next page isvisible 
    CGFloat pageWidth = self.scrollView.frame.size.width; 
    int page = floor((self.scrollView.contentOffset.x - pageWidth/2)/pageWidth) + 1; 
    self.pageControl.currentPage = page; 
} 
} 
- (IBAction)changePage { 
// update the scroll view to the appropriate page 
CGRect frame; 
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage; 
frame.origin.y = 0; 
frame.size = self.scrollView.frame.size; 

[self.scrollView scrollRectToVisible:frame animated:YES]; 
pageControlBeingUsed = YES; 

} 

@end 

Я загрузке этой ячейки в виде таблицы следующим

static NSString *CellIdentifier = @"ScrollViewCell"; 

ScrollViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[[ScrollViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 

} 


return cell; 

Когда я запускаю это приложение, он показывает пустой стол с нужной высотой, но ничего в нем. Правильно ли мой подход? если да, то чего нет?

Благодаря уважением Вишал

ответ

2

Вы пытаетесь добавить свой UIScrollView в класс UITableViewCell, я не уверен, будет ли он работать.

вместо этого попытаться, как это в вашем UITableView класса cellForRowAtIndexPath,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{  
    static NSString * CellIdentifier = @"GroupButtonCell"; 
    CustomCell * cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) 
    { 
     NSArray * customcellArray = [[NSBundle mainBundle]loadNibNamed:@"CustomCell" owner:self options:nil]; 
     for(id customcellObject in customcellArray){ 
      if([customcellObject isKindOfClass: [UITableViewCell class]]){ 
       cell = (CustomCell *)customcellObject; 
       break; 
      } 
     } 
    } 

// Customize your UIScrollView here.. 

    [cell.scrollView setDelegate:self]; 
    [cell.scrollView setPagingEnabled:YES]; 

    NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor],[UIColor blueColor], nil]; 
    cell.scrollView.contentSize = CGSizeMake(cell.scrollView.frame.size.width * colors.count,cell.scrollView.frame.size.height); 
    for (int i = 0; i < colors.count; i++) { 
     CGRect frame; 
     frame.origin.x = cell.scrollView.frame.size.width * i; 
     frame.origin.y = 0; 
     frame.size = cell.scrollView.frame.size; 

     UIView *subview = [[UIView alloc] initWithFrame:frame]; 
     subview.backgroundColor = [colors objectAtIndex:i]; 
     [cell.scrollView addSubview:subview]; 
    } 
    // Configure the cell... 

    return cell; 
} 
+0

привет, его работа по крайней мере, но я все еще не могу добавить элемент управления страницы к нему, я попробую и дам вам знать –

+0

мой вопрос теперь, если мы рисуем все в методе cellForIndexPath то в чем смысл использования XIB? Я установил цвет фона tabelcell серым, но ячейка в таблице кажется белой, что может быть причиной? –

+0

Спасибо, что сработало! –

0

попробовать это в ScrollViewCell.m Внутри метода инициализации.

 [self.contentView addSubview:scrollView]; 

Вы должны добавить scrollview на ячейку. Проверьте M не уверен. У меня было время попробовать в проекте.

+0

пробовал, но без толку, ничего работать же пустую ячейку не появится –

+1

Также вы должны Alloc INIT Scrollview – Durgaprasad

+0

ОК Вот что-то я не понимаю, будучи новичком может вы говорите мне о возможном синтаксисе? поскольку scrollview уже есть в файле XIB –

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