2015-10-21 3 views
0

Очень просто создать простой TableView с одним типом строки. Вы просто установитьНесколько RowTypes в TableView - watchKit

tableView.setNumberOfRows(yourArray.count, withRowType: "yourowtype") 

, а затем добавить цикл, чтобы заполнить ваш uilabel или что вы имеете с данными из массива.

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

tableView.setRowTypes(yourRowTypesArray) 

, но я не понимаю остальных.

В прошивке у вас есть очень четкое и простая indexPath.row решения в cellForRowAtIndexPath, где вы можете сказать - Хорошо, я хочу этот массив, чтобы заполнить эти indexPaths, другой массив должен заполнить эти e.t.c. с простой IF условной.

В WatchKit, однако, нет такой вещи, как indexPath.row, и мне непонятно, как вы можете назначить определенные номера строк для определенного массива? И почему вы должны удалить setNumberOfRows (как я видел в примерах по всей сети) в решении с несколькими рядами?

Я просмотрел сеть в отношении проблемы, и я не смог найти достойное работоспособное решение. Просто трюки и обходные пути.

спасибо.

UPDATE: Добавление кодов

Мои массивы

var questionsList = [["[What is the color of?]"],["Which city is the capital of Great Britain", "additional info"],["Some question"]] 
var answersList1 = [["Blue"],["London"],["some answer 1"]] 
var answersList2 = [["Grey"],["Liverpool"],["some answer 2"]] 

loadTable функция

private func loadTable(){ 
    tableView.setRowTypes(rowTypes) 

    for i in 0 ..< questionsList[0].count { 
     let rowController = tableView.rowControllerAtIndex(i) as! TableViewRowController 
     rowController.lblQuestion.setText(questionsList[0][i]) 
    } 

    let rowController1 = tableView.rowControllerAtIndex(answersList1[0].count) as! AnswerRowController1 
    rowController1.button1.setTitle(answersList1[0][0]) 

    let rowController2 = tableView.rowControllerAtIndex(answersList2[0].count+1) as! AnswerRowController2 
    rowController2.button2.setTitle(answersList2[0][0]) 
} 

ответ

2

Я предпочел бы предложить вам для уточнения модели. Это очень сложно понять. Рефакторируйте его в класс или структуру, чтобы было легко понять.

Вот мой подход, чтобы реорганизовать его немного и создать своего рода вещи, которые вы хотели,

let QuestionRowIdentifier = "QuestionRowIdentifier" 
let AnswerRowIdentifier = "AnswerRowIdentifier" 
let QuestionSeparatorRowIdentifier = "QuestionSeparatorIdentifier" 


protocol QuestionAnswerRowTypes { 
    var titleLabel: WKInterfaceLabel! { get set } 
} 

class QuestionRowController: NSObject, QuestionAnswerRowTypes { 
    @IBOutlet var titleLabel: WKInterfaceLabel! 
} 

class AnswerRowController: NSObject, QuestionAnswerRowTypes { 
    @IBOutlet var titleLabel: WKInterfaceLabel! 
} 

struct Question { 
    let title: String 
    let additionalInfo: String? 
    let answers: [String] 
} 

let questions = [ 
    Question(title: "What is the color of?", additionalInfo: nil, answers: [ 
     "Blue", 
     "Gray" 
    ]), 
    Question(title: "Which city is the capital of Great Britain?", additionalInfo: "additional info", answers: [ 
      "London", 
      "Liverpool" 
     ]), 
    Question(title: "Some question?", additionalInfo: nil, answers: [ 
     "some answer 1", 
     "some answer 2" 
     ]) 
] 

class InterfaceController: WKInterfaceController { 

    @IBOutlet private var tableView: WKInterfaceTable! 

    var names = ["Alexander", "Ferdinand", "Jack", "Samuel", "Thompson", "Tony"] 

    override func awakeWithContext(context: AnyObject?) { 
     super.awakeWithContext(context) 

     let rowTypes = getRowTypes() 

     tableView.setRowTypes(rowTypes) 

     for i in 0 ..< rowTypes.count { 
      if let rowController = tableView.rowControllerAtIndex(i) as? QuestionAnswerRowTypes { 
       rowController.titleLabel.setText(textAtIndex(i)!) 
      } 
     } 
    } 

    func getRowTypes() -> [String] { 
     return questions.flatMap { question in 
      return [ 
       [QuestionRowIdentifier], 
       Array(count: question.answers.count, repeatedValue: AnswerRowIdentifier), 
       [QuestionSeparatorRowIdentifier] 
       ].flatMap { $0 } 
     } 
    } 

    func textAtIndex(index: Int) -> String? { 
     let titles = questions.flatMap { question in 
      return 
      [ 
       [Optional.Some(question.title)], 
       question.answers.map(Optional.Some), 
       [Optional.None], 
      ] 
     }.flatMap({ $0 }) 
     return titles[index] 
    } 
} 

А вот конечный результат,

enter image description here

+0

мне удалось заставить его работать. Но в статической версии. Другая проблема - у меня есть три массива в виде трех отдельных источников данных для разных типов строк. И эти массивы обновляются динамически. Неясно, как можно различать эти типы строк, поскольку нет разделов или indexPath.rows ... –

+0

Добавлены коды. Моя цель состоит в том, чтобы иметь возможность 1) Альтернативно между вопросамиВыберите ячейки и ответыList1, ячейки answerList2 и загрузите соответствующий класс с идентификатором 2) Подайте данные из массивов таким образом, чтобы они были похожи на «ячейка вопроса/ячейка вопроса» \ answer 1 cell \ answer 1 cell "then again" question 2 cell \ question 2 cell \ answer 1 cell \ answer 1 cell "и т. д. в зависимости от размера массива –

+0

@DavidRobertson, см. мои изменения – Sandeep

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