2017-01-21 3 views
0

У меня есть UIView в пользовательском представлении, которое я построил с помощью xib. Мне нужно отобразить UITableView в указанном представлении. Сначала я подумал о размещении container и встраивании в него UITableViewController. Оказывается, я не могу разместить containers в файле xib, или, по крайней мере, нет способа сделать это из IB, поскольку он не отображается в виде в правом нижнем углу.Как вставить UITableView в UIView?

Я могу создать программный код UITableView и добавить его в качестве подвид представления. Он отображается как ожидалось, но я не могу добавить в него ячейки. Я также попытался создать в ассоциации хорошо ведет себя UITableViewController с storyboard зрения, экземпляр этого контроллера следующим образом:

let storyboard = (UIStoryboard(name: "Main", bundle: nil)) let vc = storyboard.instantiateViewControllerWithIdentifier("tableViewController") as! TestTableViewController

, а затем пытались доступ к Розеткам UITableView «s, который был nil. Затем я где-то читал, что должен делать vc.loadView(), потому что, как следует из названия, он загружает представление, а мой IBOutlet не будет nil. Это сработало. Выход был длиннее nil. Но, когда я добавляю таблицу в представление контейнера в качестве подзаголовка, он по-прежнему не показывает никаких ячеек. Существуют только разделительные линии, но нет содержимого. У меня кончились идеи!

EDIT

У меня нет никаких UITableViewCell реализаций, как таблицы являются статическими.

ответ

0

Хороший подход заключается в использовании UITableView внутри пользовательского вида:

если вы добавляете Tableview программно затем зарегистрировать ячейку с помощью СИБ или UITableView подкласса, как

tableView.registerNib(UINib(nibName: "UITableViewCellSubclass", bundle: nil), forCellReuseIdentifier: "UITableViewCellSubclass") 

, если вы создаете UITableViewCell с помощью XIb ,

tableView.registerClass(UITableViewCellSubclass.self, forCellReuseIdentifier: "UITableViewCellSubclass") // using code. 
tableView.delegate = self 
tableView.dataSource = self 

, а затем использовать 2 требуемых делегата.

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
return 2 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
return tableView.dequeueReusableCellWithIdentifier("UITableViewCellSubclass", forIndexPath: indexPath) as! UITableViewCellSubclass 
} 

надеюсь, что я ответил на ваш вопрос.

+0

, если это делает никакой разницы, таблица является статическим. его содержимое остается неизменным. – JadeSync

+0

Фактически я забыл упомянуть, у меня нет реализаций UITableViewCell, так как мои таблицы являются статическими – JadeSync

0

Objective C Вы должны делегатов в вашем ViewController, если у вас есть ViewController, поставить делегат таблицы:

UIViewController UITableViewDelegate UITableViewDataSource

И вы можете использовать функции

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; //count of section 
} 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    return [catagorry count]; //count number of row from counting array hear cataGorry is An Array 
} 



- (UITableViewCell *)tableView:(UITableView *)tableView 
      cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
     static NSString *MyIdentifier = @"MyIdentifier"; 

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 

     if (cell == nil) 
     { 
      cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
              reuseIdentifier:MyIdentifier] autorelease]; 
     } 

     // Here we use the provided setImageWithURL: method to load the web image 
     // Ensure you use a placeholder image otherwise cells will be initialized with no image 
     [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] 
         placeholderImage:[UIImage imageNamed:@"placeholder"]]; 
      cell.textLabel.text = @"My Text"; 
     return cell; 
    } 

Свифт:

делегат: UIViewController UITableViewDataSource UITableViewDelegate

override func viewDidLoad() { 
    super.viewDidLoad() 

    tableView.delegate = self 
    tableView.dataSource = self 
} 

Swift

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) 

    let row = indexPath.row 
    cell.textLabel?.text = swiftBlogs[row] 

    return cell 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) 

    let row = indexPath.row 
    cell.textLabel?.text = swiftBlogs[row] 

    return cell 
} 


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return swiftBlogs.count 
} 


func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

Посмотреть больше More inf

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