iPhone: UITableView с пользовательскими ячейками для настроек

Если вы действительно хотите сделать это, чтобы передать свой массив, я предлагаю реализовать структуру для хранения указателя на тип, который вам нужен, массив и целое число, представляющее размер массива. Затем вы можете передать это своим функциям. Просто присвойте значение переменной массива (указатель на первый элемент) этому указателю. Затем вы можете пойти Array.arr[i], чтобы получить i-й элемент, и использовать Array.size, чтобы получить количество элементов в массиве.

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

/* Absolutely no one should use this...
   By the time you're done implementing it you'll wish you just passed around
   an array and size to your functions */
/* This is a static implementation. You can get a dynamic implementation and 
   cut out the array in main by using the stdlib memory allocation methods,
   but it will work much slower since it will store your array on the heap */

#include <stdio.h>
#include <string.h>
/*
#include "MyTypeArray.h"
*/
/* MyTypeArray.h 
#ifndef MYTYPE_ARRAY
#define MYTYPE_ARRAY
*/
typedef struct MyType
{
   int age;
   char name[20];
} MyType;
typedef struct MyTypeArray
{
   int size;
   MyType *arr;
} MyTypeArray;

MyType new_MyType(int age, char *name);
MyTypeArray newMyTypeArray(int size, MyType *first);
/*
#endif
End MyTypeArray.h */

/* MyTypeArray.c */
MyType new_MyType(int age, char *name)
{
   MyType d;
   d.age = age;
   strcpy(d.name, name);
   return d;
}

MyTypeArray new_MyTypeArray(int size, MyType *first)
{
   MyTypeArray d;
   d.size = size;
   d.arr = first;
   return d;
}
/* End MyTypeArray.c */


void print_MyType_names(MyTypeArray d)
{
   int i;
   for (i = 0; i < d.size; i++)
   {
      printf("Name: %s, Age: %d\n", d.arr[i].name, d.arr[i].age);
   }
}

int main()
{
   /* First create an array on the stack to store our elements in.
      Note we could create an empty array with a size instead and
      set the elements later. */
   MyType arr[] = {new_MyType(10, "Sam"), new_MyType(3, "Baxter")};
   /* Now create a "MyTypeArray" which will use the array we just
      created internally. Really it will just store the value of the pointer
      "arr". Here we are manually setting the size. You can use the sizeof
      trick here instead if you're sure it will work with your compiler. */
   MyTypeArray array = new_MyTypeArray(2, arr);
   /* MyTypeArray array = new_MyTypeArray(sizeof(arr)/sizeof(arr[0]), arr); */
   print_MyType_names(array);
   return 0;
}
1
задан Nic Hubbard 13 May 2010 в 22:19
поделиться

2 ответа

Для начала установите для свойства tableViewStyle значение UITableViewStyleGrouped . Затем измените источник данных чтобы предоставить 2D-массивы с нужными вам группами вместо простого массива. На самом деле это довольно просто.

Вам нужно будет настроить строку с типами UIControl , которые вы хотите - хотя я предполагаю, что вы уже это делаете.

РЕДАКТИРОВАТЬ:

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

...
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setFrame:CGRectMake(0.0f, 5.0f, 30.0f, 30.0f)];

[button setTitle:@"Click Me!" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:button];
...
2
ответ дан 3 September 2019 в 00:33
поделиться

Вы можете сделать это без массива. Просто используйте следующие методы

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

и затем можете использовать switch-метод для разбора всех строк и секций. Эти две строки в заголовке методов сверху и вы можете немного сократить его.

NSUInteger row = [indexPath row];
NSUInteger section = [indexPath section];

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

cheers Simon

0
ответ дан 3 September 2019 в 00:33
поделиться
Другие вопросы по тегам:

Похожие вопросы: