Логика для добавления изображений и значка прокрутки к представлению таблицы - PullRequest
0 голосов
/ 09 июня 2011

У меня есть табличное представление, и я добавляю четыре UIImageView s к строке, так что в общей сложности у меня есть пять строк и двадцать изображений. Я вставляю изображения по одному в клетку. Второй ряд начнет заполняться только после заполнения всех четырех видов изображений.

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

Также есть ли способ индивидуально выбрать изображения из ряда?

Ответы [ 4 ]

1 голос
/ 09 июня 2011

Запустите этот код: -

.h file code


#import <UIKit/UIKit.h>

@interface helpTableViewController : UIViewController {
    IBOutlet UITableView *gridTableView;
    NSMutableArray *imagesArray;
    int widthview,widthview1;

    }
@property(nonatomic,retain)NSMutableArray *imagesArray;
@property(nonatomic,retain)UITableView *gridTableView;
-(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath;
-(void)crossViewButtonClicked:(UIButton *)sender;

@end

.m Код файла: -

@synthesize gridTableView;
@synthesize imagesArray;


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    NSMutableArray *tempArray=[[NSMutableArray alloc]init];
    self.imagesArray=tempArray;
    [tempArray release];
    [self.imagesArray addObject:[UIImage imageNamed:@"pic1.png"]];
    [self.imagesArray addObject:[UIImage imageNamed:@"pic2.png"]];
    [self.imagesArray addObject:[UIImage imageNamed:@"pic3.png"]];
    [self.imagesArray addObject:[UIImage imageNamed:@"pic4.png"]];
    [self.imagesArray addObject:[UIImage imageNamed:@"pic5.png"]];
    [self.imagesArray addObject:[UIImage imageNamed:@"pic6.png"]];
    [self.imagesArray addObject:[UIImage imageNamed:@"pic1.png"]];
    [self.imagesArray addObject:[UIImage imageNamed:@"pic2.png"]];
    [self.imagesArray addObject:[UIImage imageNamed:@"pic3.png"]];
    widthview=0;
    widthview1=0;
}

- (void)viewDidUnload {
    self.gridTableView=nil;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [imagesArray release];
    [gridTableView release];
    [super dealloc];
}


#pragma mark -
#pragma mark TableView Methods

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


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell=nil;
    if (cell == nil) {
        cell =[self reuseTableViewCellWithIdentifier:CellIdentifier withIndexPath:indexPath];

    }

            return cell;
}
-(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:identifier]autorelease];
    if (indexPath.row==0) {
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
        scrollView.contentSize = CGSizeMake(320, 180);
        scrollView.backgroundColor=[UIColor clearColor];
        scrollView.showsHorizontalScrollIndicator = NO;
        [cell.contentView addSubview:scrollView];       
        for (int i=0; i<4;i++) {        
            UIView *profileView=[[UIView alloc]initWithFrame:CGRectMake(widthview+10, 12, 95, 155)];
            profileView.backgroundColor=[UIColor whiteColor];
            UIImageView *profileimageView=[[UIImageView alloc]initWithFrame:CGRectMake(5, 8, 83, 106)];
            [profileimageView setImage:[self.imagesArray objectAtIndex:i]];
            profileimageView.tag=i+90;
            [profileView addSubview:profileimageView];
            [profileimageView release];
            [scrollView addSubview:profileView];
            widthview=widthview+105;
            NSLog(@"%d",widthview);
        }
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setFrame:CGRectMake(widthview1+10, 12, 95, 155)];
        //button.contentMode = UIViewContentModeScaleAspectFill;
        button.tag=999999;
        [button setBackgroundColor:[UIColor greenColor]];
        [button addTarget:self action:@selector(imageButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [scrollView addSubview:button];
        widthview=widthview+105;
        scrollView.contentSize = CGSizeMake(widthview, 180);

    }
    if (indexPath.row==1) {
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
        scrollView.contentSize = CGSizeMake(320, 180);
        scrollView.backgroundColor=[UIColor clearColor];
        scrollView.showsHorizontalScrollIndicator = NO;
        [cell.contentView addSubview:scrollView];       
        for (int i=0; i<4;i++) {        
            UIView *profileView=[[UIView alloc]initWithFrame:CGRectMake(widthview1+10, 12, 95, 155)];
            profileView.backgroundColor=[UIColor whiteColor];

            UIImageView *profileimageView=[[UIImageView alloc]initWithFrame:CGRectMake(5, 8, 83, 106)];
            //  [profileimageView setImage:[UIImage imageNamed:@"gridimage1.png"]];
            profileimageView.tag=4+i;
            [profileimageView setImage:[self.imagesArray objectAtIndex:3+i]];
            [profileView addSubview:profileimageView];

            [scrollView addSubview:profileView];
            [profileimageView release];
            widthview1=widthview1+105;
            NSLog(@"%d",widthview1);
        }
        scrollView.contentSize = CGSizeMake(widthview1, 180);

    }return cell;

}

// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}
#pragma mark -
#pragma mark button methods


-(void)imageButtonClicked:(UIButton *)sender
{
    [self.imagesArray replaceObjectAtIndex:0 withObject:[UIImage imageNamed:@"abdulprofilepic.png"]];
    [self.gridTableView reloadData];

}
1 голос
/ 09 июня 2011

попробуйте это, так как есть фиксированное количество изображений, которые вы хотите показать в вашей строке, т.е. 4 Итак, что вам нужно сделать, это: - в файле .h

int widthview,widthview1;

в файле .m вviewdidload

   widthview=0;
    widthview1=0;



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
       cell = [self reuseTableViewCellWithIdentifier:CellIdentifier withIndexPath:indexPath];

    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;//to remove blu selection color
    return cell;
}
-(UITableViewCell *)reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:identifier]autorelease];
    if (indexPath.row==0) {
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
        scrollView.contentSize = CGSizeMake(320, 180);
        scrollView.backgroundColor=[UIColor clearColor];
        scrollView.showsHorizontalScrollIndicator = NO;
        [cell.contentView addSubview:scrollView];       
        for (int i=0; i<4;i++) {        
            UIImageView *profileimageView=[[UIImageView alloc]initWithFrame:CGRectMake(widthview+10, 12, 95, 155)];
            [profileimageView setImage:[self.imagesArray objectAtIndex:i]];
            [profileimageView release];
            [scrollView addSubview:profileimageView];
            widthview=widthview+105;
            NSLog(@"%d",widthview);
        }
        scrollView.contentSize = CGSizeMake(widthview, 180);

    }
    if (indexPath.row==1) {
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 180)];
        scrollView.contentSize = CGSizeMake(320, 180);
        scrollView.backgroundColor=[UIColor clearColor];
        scrollView.showsHorizontalScrollIndicator = NO;
        [cell.contentView addSubview:scrollView];       
        for (int i=0; i<4;i++) {        
            UIImageView *profileimageView=[[UIImageView alloc]initWithFrame:CGRectMake(widthview+10, 12, 95, 155)];
            [profileimageView setImage:[self.imagesArray objectAtIndex:4+i]];
            [profileimageView release];
            [scrollView addSubview:profileimageView];
            widthview1=widthview1+105;
            NSLog(@"%d",widthview1);
    }
        scrollView.contentSize = CGSizeMake(widthview1, 180);

    }
return cell;

}

Этот код для 2 строк делает то же самое для следующих трех строк.Отрегулируйте координаты в соответствии с вашими требованиями.надеюсь, это сэкономит ваше время.

1 голос
/ 09 июня 2011

Вы должны хранить всю логику (и данные) в вашем контроллере табличного представления (UITableViewController подкласс).Я предлагаю вам иметь собственный подкласс UITableViewCell, который может содержать 4 изображения (сама ячейка должна отвечать за макет), а контроллер представления таблицы отвечает за его настройку.В -tableView:cellForRowAtIndexPath: вы можете просмотреть свою коллекцию изображений, а затем просто использовать модульная арифметика , чтобы выяснить, какие изображения должны быть в ячейке для этого конкретного пути индекса.

Что касается индивидуального выбораизображения, возможно, вы могли бы, чтобы ваши ячейки знали свой путь индекса (установленный как пользовательское свойство в -tableView:cellForRowAtIndexPath:), тогда у каждого был бы метод делегата, сообщающий вашему контроллеру, что определенное изображение было нажато (например, -cellAtIndexPath:didSelectImageAtIndex:).

0 голосов
/ 09 июня 2011

ответ для Также есть ли способ индивидуально выбрать изображения из ряда?: Дайте изображение кнопке и добавьте эту кнопку в ряд !!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...