0

I'm playing around with custom cells. With the great help from the stackoverflow community i've been able to put some code together. I'm able to fetch array values from a text string into a custom cell uilabel and uibutton, but the issue is - the fetched result is always the last object in the array.

Here is the code

func setUpQuestion()
{

// setting variables
var Question: String?
var option1: String?


// using a text string with custom separators

    let text = ">>Here is the grocery question\n>>and another one\n--Apples\n-
-Oranges\n[pickApples]pickOranges\n[pickApples2]"

// splitting this string into four different arrays depending on the separator 

    let lines = split(text) { $0 == "\n" }
    for line in lines {
        if line.hasPrefix(">>") {
            Question = line.substringFromIndex(advance(line.startIndex, 2))
        } else if line.hasPrefix("[") {
            if let index = line.rangeOfString("]")?.startIndex {
                option1 = line.substringWithRange(Range<String.Index>(
                    start: advance(line.startIndex, 1), end: index))
            }
        }
    }

// creating variables for appending the values - here I'm using a custom class called QuestionMark created in a separate .swift file 

    var question1 = QuestionMark(Question: Question!, option:option1!)
    var question2 = QuestionMark(Question: Question!, option:option1!)

// appending the values into uilabel and uibutton in the custom cell

    arrayOfQuestions.append(question1)
    arrayOfQuestions.append(question2)

}

// regular tableView protocol functions

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

}

func updateCount(){
    if let list = mainTableView.indexPathsForSelectedRows() as? [NSIndexPath] {
        rowsCount.text = String(list.count)
    }
}
func tableView(tableView: UITableView, cellForRowAtIndexPath
    indexPath: NSIndexPath) -> UITableViewCell
{
    let cell: CustomCellForTableViewTableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! CustomCellForTableViewTableViewCell

// the SetCell function i'm using here was created in a separate .swift file

    let quest = arrayOfQuestions[indexPath.row]
    cell.setCell(quest.Questme!, optionone: quest.optionize!)

    cell.optionOne.backgroundColor = UIColor.redColor()

    return cell

}

Here are the additional codes i'm using for the class and setCell function

class QuestionMark
{

var Questme: String?
var optionize: String?

init(Question: String, option: String)
{
    self.Questme = Question
    self.optionize = option
}

// separate swift file
func setCell(Question: String, optionone: String)
{
    self.mainText.text = Question
    self.optionOne.setTitle(optionone, forState:UIControlState.Normal)
}

As a result in both cells i'm getting the last object from the text string and it looks like this

And another one - PickApples2
And another one - PickApples2

How do i start appending cells from the first array value and then move forward to second,third,fourth ?

Any ideas are greatly appreciated.

Thank you.

7
  • add the your cellForRowAtIndexPath code. so we can help you better Commented Aug 18, 2015 at 7:37
  • @Karlos, added the required code. please look in the original post. Commented Aug 18, 2015 at 7:56
  • can you try this in cellForRowAtIndexPath ----> cell.textLabel?.text = arrayOfQuestions[indexPath.row] Commented Aug 18, 2015 at 8:41
  • 1
    @Karlos, there is an issue with this approach - i'm appending values into two objects (uilabel and unbutton) using the arrayOfQuestions, not just the textLabel. The suggested method in that case would return an error. Commented Aug 18, 2015 at 8:48
  • Did you tried button.tag = indexPath.row and add all your button details to that button? Commented Aug 18, 2015 at 9:13

1 Answer 1

1

First of all, the syntax of the text to parse is pretty complicated ;-) …

Second of all, the problem to get always the last object is that you create the array of questions after the repeat loop. At that moment the variables question and option contain always the last found string.

Here a solution:

  • After getting a question a new object QuestionMark is created and appended to the array (without the optionize property)
  • After getting an option the appropriate QuestionMark object is fetched from the array by an index counter, the property optionize is set and the counter is increased.

Two notes:

  • Variable names should always start with a lowercase letter. Even the syntax highlighter of StackOverflow follows that naming convention.
  • In my solution all variables are non-optionals.

class QuestionMark
{

  var questme: String
  var optionize: String

  init(question: String, option: String = "")
  {
    self.questme = question
    self.optionize = option
  }

...

var arrayOfQuestions = [QuestionMark]()

func setupQuestion() {

  let text = ">>Here is the grocery question\n>>and another one\n--Apples\n--Oranges\n[pickApples]pickOranges\n[pickApples2]"

  // splitting this string into four different arrays depending on the separator

  var counter = 0

  var question = ""
  var option = ""

  let lines = split(text) { $0 == "\n" }
  for line in lines {
    if line.hasPrefix(">>") {
      question = line.substringFromIndex(advance(line.startIndex, 2))
      let questionMark = QuestionMark(question: question)
      arrayOfQuestions.append(questionMark)
    } else if line.hasPrefix("[") {
      if let index = line.rangeOfString("]")?.startIndex {
        option = line.substringWithRange(Range<String.Index>(
          start: advance(line.startIndex, 1), end: index))
        let questionMark = arrayOfQuestions[counter]
        questionMark.optionize = option
        counter++
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

thank you for the insight. i've tried the solution and i'm getting a blank uitableview. I'm also wondering how we fix this part of code then let quest = arrayOfQuestions[indexPath.row] cell.setCell(quest.Questme!, optionone: quest.optionize!)
sorry, re-phrasing my question a little: i've fixed the lines of code below accordingly to the solution yet still getting a blank screen let quest = arrayOfQuestions[indexPath.row] cell.setCell(quest.questme, optionone: quest.optionize)
add breakpoints and println() lines to make sure that the appropriate methods are called at all
worked amazingly! just changed the setupQuestion function spelling) my lousy mistake. thank you so much for the support!
Hi vadian! Is there a way to actually limit the output to a specific number of objects along these lines let questionMark = QuestionMark(question: question) arrayOfQuestions.append(questionMark)? In case if i just want to output 1 or 2 questions and then proceed after users input. Thank you!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.