无法在简单的Times Table App中显示Table View数据

时间:2016-05-31 17:10:46

标签: ios swift uitableview

我正在尝试使用滑块和表格视图在Swift中制作一个简单的Times Table App(数字1-9)。我正在设法使滑块工作,并为使用滑块选择的每个数字创建一个数组,尽管数组显示在控制台上。我无法将数字显示在表格视图中。你能帮帮我,告诉我我错过了什么吗?

这是我到目前为止所写的内容:

class ViewController: UIViewController, UITableViewDelegate {

    @IBOutlet var sliderValue: UISlider!

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

    @IBAction func sliderMoved(sender: UISlider) {
        sender.setValue(Float(lroundf(sliderValue.value)), animated: true)

        print(sliderValue)

        var cellContent = [String]()

        for var i = 1; i <= 10; i += 1 {
            cellContent.append(String(i * Int(sliderValue.value)))
        }

        print(cellContent)

        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

            cell.textLabel?.text = cellContent[indexPath.row]

            return cell
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

3 个答案:

答案 0 :(得分:1)

您是否尝试过将cellContent数组创建为实例变量,以下代码可能有效。检查一次。

var cellContent = [String]()
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 9
}

@IBAction func sliderMoved(sender: UISlider) {
    sender.setValue(Float(lroundf(sliderValue.value)), animated: true)

    print(sliderValue)



    for var i = 1; i <= 10; i += 1 {
        cellContent.append(String(i * Int(sliderValue.value)))
    }

    print(cellContent)

    self.tableview.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

        cell.textLabel?.text = cellContent[indexPath.row]

        return cell
    }
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

答案 1 :(得分:1)

我担心你所提供的代码中有相当多的东西并没有多大意义。我在上面的评论中已经提到了一些内容,但您也将看起来像tableViewDataSource函数的内容嵌套到了sliderMoved函数中。整个数组看起来相当不错,并且建议的单元数实际上并不考虑数组的大小。我认为你可能想要这样的东西:

class ViewController: UIViewController, UITableViewDataSource {
    @IBOutlet var valueSlider: UISlider!
    @IBOutlet var tableView: UITableView!
    private var cellContent = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
    }

    @IBAction func sliderMoved(sender: UISlider) {
        sender.setValue(Float(lroundf(valueSlider.value)), animated: true)
        tableView.reloadData()
    }

    // TableViewDataSource

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") // Must exist with the same identifier in your storyboard
        cell.textLabel?.text = valueStringForIndex(indexPath.row)

        return cell
    }

    // Private functions

    private func valueStringForIndex(index: Int) -> String {
        return "\(index * Int(valueSlider.value))"
    }
}

答案 2 :(得分:0)

虽然不能直接回答您的问题 - &gt;

根据您希望表格显示的方式,UICollectionView可能非常适合此应用程序。非常类似于UITableView实现,但是使用框和列数据,可能更容易格式化(并且更改滑块可以在集合视图更新时添加一些有趣的动画)。

下面的示例UIViewController演示了如何使用UICollectionView。在故事板中,我只是:

  • 在MultiplicationTableViewController中添加了UISlider,UICollectionView和UILabel并创建了出口
  • 在UICollectionView默认单元格中,我为其提供了reuseIdentifier“numberCell”,并添加了一个标签(用于存放产品)
  • 使MultiplicationTableViewController成为UICollectionView的dataSource和委托

<强> CODE:

import UIKit

class MultiplicationTableViewController: UIViewController {

  @IBOutlet var timesTableCollectionView: UICollectionView!
  @IBOutlet weak var numberSlider: UISlider!
  @IBOutlet weak var label: UILabel!

  var products = [Int]()   //array to hold the computed value for each cell in the collectionView

  override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.viewRotated), name: UIDeviceOrientationDidChangeNotification, object: nil)  //register for rotation notifications
    products = createTableOfValues()             //populate products with initial values
    label.text = "\(Int(numberSlider.value)) x \(Int(numberSlider.value))"
  }

  @IBAction func sliderUpdated(sender: UISlider) {
    sender.value = Float(Int(sender.value))      //make the slider stop only on whole numbers
    label.text = "\(Int(sender.value)) x \(Int(sender.value))"
    products = createTableOfValues()             //create the new table values
    timesTableCollectionView.reloadData()        //tell the collectionView to read the new data and refresh itself
  }

  func createTableOfValues() -> [Int] {
    var prod = [Int]()                           //temp array to hold the generated products
    for row in 0...Int(numberSlider.value) {     //iterate from row 0 (header) to
      var columns = [Int]()                      //temp array to build column products
      for column in 0...Int(numberSlider.value) {//iterate through each column, including column 0 (header)
        if column == 0 {
          columns.append(row)
        } else if row == 0 {
          columns.append(column)
        } else {
          columns.append(column * row)
        }
      }
      prod.appendContentsOf(columns)             //add the current row of products to the temp array
    }
    return prod
  }

  func viewRotated() {
    timesTableCollectionView.reloadData()        //called to force collectionView to recalc (basically to get new cell sizes
  }
}

extension MultiplicationTableViewController: UICollectionViewDataSource {

  func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1                                    //required for UICollectionViewDataSource
  }

  func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return Int(numberSlider.value + 1) * Int(numberSlider.value + 1)   //tells the UICollectionView how many cells to draw (the number on the slider, plus header rows)
  }

  func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("numberCell", forIndexPath: indexPath)   //get an existing cell if it exists
    if cell.frame.origin.y == 0.0 || cell.frame.origin.x == 0.0 {     //if the cell is at the top or left of the collectionView
      cell.backgroundColor = UIColor.yellowColor()
    } else {
      cell.backgroundColor = UIColor.clearColor()                     //If not, reset the color (required because cells are reused
    }
    cell.layer.borderColor = UIColor.blackColor().CGColor
    cell.layer.borderWidth = 1.0
    let numberItem = cell.viewWithTag(101) as? UILabel               //get a reference to the label in the current cell
    numberItem?.text = String(products[indexPath.row])               //get the value generated earlier for this particular cell
    return cell
  }
}

extension MultiplicationTableViewController: UICollectionViewDelegateFlowLayout {
  func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let columns = CGFloat(numberSlider.value + 1)                       //get the number of columns - slider value + 1 for header
    let width = timesTableCollectionView.bounds.width / columns         //divide the width of the collectionView by the number of columns
    return CGSizeMake(width, width)                                     //use width value to make the cell a square
  }
}

<强>截图: enter image description here