【问题标题】:UITableView inside a ViewController with custom cell without storyboard带有自定义单元格的 ViewController 内的 UITableView 没有情节提要
【发布时间】:2016-01-19 12:59:21
【问题描述】:

我正在使用 Swift 2.0 和 Xcode 7.2。

我想学习如何制作没有情节提要的应用(带有纯编程代码的 UI)。首先,我尝试在自定义 UITableView 单元格中制作一个简单的应用程序,其中包含三个标签,该单元格将通过互联网动态更新。

这是我到目前为止所取得的成就:

  • 创建了一个新的 Swift 项目并从项目中删除了 main.storyboard
  • AppDelegate 中添加了一个视图控制器作为rootViewController
  • 包含在此视图中创建 UITableView 的代码

以下是我想要完成的其他任务(全部以编程方式,不使用属性检查器):

  • UINavigationController 插入ViewController
  • 添加具有三个标签的自定义单元格
  • 用数据更新表格视图

如果可能的话,我希望能够让一切都在横向模式下工作。

谁能告诉我怎么做?

AppDelegate.swift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window!.backgroundColor = UIColor.whiteColor()
    window!.rootViewController = ViewController()
    window!.makeKeyAndVisible()
    return true
}

ViewController.swift

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.whiteColor()


        tableView.frame = CGRectMake(0 , 0, self.view.bounds.width, self.view.bounds.height)//Optional for table size

        self.view.addSubview(tableView)
    }

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let myCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "myIdentifier")

        myCell.textLabel?.text = "\(indexPath.row)"
        myCell.detailTextLabel?.text = "Subtitle"

        return myCell
    }

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

我不知道如何以编程方式创建一个可以添加对象的自定义单元格。

我们将不胜感激。

谢谢。

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    如果您不使用情节提要,您可以在您的 ViewController 包含您的 tableView 的类上方定义您的单元格,例如 myCell ,这是您的自定义 UITableViewCell,如下所示。

    在这个 myCell 中,您可以根据需要添加任意数量的对象,并将它们设置在 setUpCell() 块中。

    完整代码如下,在cellForRowAtIndexPath使用手机时请务必拨打setUpCell()

    ViewController.swift

    import #UIKit
    
    class myCell: UITableViewCell {
    
        // Define label, textField etc
        var aMap: UILabel!
    
        // Setup your objects
        func setUpCell() {
            aMap = UILabel(frame: CGRectMake(0, 0, 200, 50))
            self.contentView.addSubview(aMap)
        }
    }
    
    
    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
        var tableView = UITableView()
        // for ex, lets say, your data array is defined in the variable below
        var dataArray = [[String:AnyObject]]() //Array of your data to be displayed
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view, typically from a nib.
    
            tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
            tableView.dataSource = self
            tableView.delegate = self
            tableView.backgroundColor = UIColor.whiteColor()
    
            // register your class with cell identifier
            self.tableView.registerClass(myCell.self as AnyClass, forCellReuseIdentifier: "Cell")
    
            self.view.addSubview(tableView)
    
            dataArray = // Something loaded from internet 
        }
    
        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return flightDataArr.count
        }
    
        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
           // let myCell = tableView.dequeueReusableCellWithIdentifier("myIdentifier", forIndexPath: indexPath)
    
            var cell:myCell? = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? myCell
    
            if cell == nil {
                cell = myCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
            }
            var data = dataArray[indexPath.row]
            cell?.setUpCell()
            cell!.aMap.text = String(dict["productName"])
            return cell!
        }
    }
    

    看看这是否适合你。我从未使用编程来创建tableView,因此这可能不是以编程方式创建tableView 的最佳方式。如果可能的话,我希望其他人可以帮助您提供更好的答案。

    【讨论】:

      【解决方案2】:

      你可以创建一个 UITableViewCell 的子类,比如 PackageListTableViewCell。

      根据您的要求在 tabelViewCell 自定义类中声明标签的数量,如下所示,

      var label1 : UILabel?;
      

      使用以下附加参数覆盖自定义单元格中的init:reuseIdentifier:

              override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
          super.init(style: style, reuseIdentifier: reuseIdentifier)
      
                  //create labels as per your requirement
      
      
                 self.label1 = //initialise you label
                 //set frame, or constraint
                 //set text color, background color etc
      
                  //add created labels to cell as below
                 self.contentView.addSubView(self.label1);          
      
          }
      

      你的tableView:cellForRowAtIndexPath: 看起来像,

      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      
              let lable1String = "lbl1"
              let lable2String = "lbl2"
              let lable3String = "lbl3"
      
              var cell : PackageListTableViewCell! = tableView.dequeueReusableCellWithIdentifier("cellID") as?PackageListTableViewCell
      
              if (cell == nil) {
                  cell = PackageListTableViewCell.init(style: UITableViewCellStyle.Default,
                      reuseIdentifier:"cellID");
      
              }
      
              cell.selectionStyle = UITableViewCellSelectionStyle.None;
              //set text of your lables as below
              cell.label1.text = lable1String;
      
              return cell;
          }
      

      【讨论】:

      • 我创建了一个新的 UITableViewCell 类 PackageListTableViewCell。但我不确定什么是 Product 和 StoreProduct?我收到错误“使用未声明的类型”。我应该如何使用它?
      • 你可以去掉那些参数,那些参数是我的自定义数据,
      • 在代码中阅读这个链接,这样你就会明白了,//根据你的要求更改参数,或者你可以删除除style:reuseIdentifier:之外的其他参数
      • 这消除了一些错误,但现在我不确定如何使用“Constant.cellID”作为标识符?因此,我不确定如何使用 if (cell == nil) { cell = PackageListTableViewCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier, storeProduct: storeProduct, package: package);我在这方面很新,总是使用故事板。您能否编辑所有与自定义数据相关的内容并使其与问题更相关。这真的很有帮助。我会非常感谢你的努力。
      • @VickyArora Hitendra 代码运行良好,唯一的问题是您现在缺少 cellForRowAtIndexPath 中的 cell.clipsToBounds = true。添加后,此代码应该可以工作。所有功劳归于这篇文章:stackoverflow.com/questions/22358831/…
      【解决方案3】:

      您必须使用 tableview 上的 registerClass 方法注册自定义 tableviewcell 类。

      使用修改后的 Viewcontroller 代码:

      class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
      
      var tableView = UITableView()
      
      override func viewDidLoad() {
          super.viewDidLoad()
      
          // Do any additional setup after loading the view, typically from a nib.
      
          tableView = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain)
          tableView.dataSource = self
          tableView.delegate = self
          tableView.backgroundColor = UIColor.whiteColor()
      
          tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myIdentifier")
      
          tableView.frame = CGRectMake(0 , 0, self.view.bounds.width, self.view.bounds.height)//Optional for table size
      
          self.view.addSubview(tableView)
      }
      
      func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          return 5
      }
      
      func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
      
          let myCell = tableView.dequeueReusableCellWithIdentifier("myIdentifier", forIndexPath: indexPath)
          myCell.textLabel?.text = "\(indexPath.row)"
          myCell.detailTextLabel?.text = "Subtitle"
      
          return myCell
      }
      
      override func didReceiveMemoryWarning() {
          super.didReceiveMemoryWarning()
          // Dispose of any resources that can be recreated.
      }
      

      }

      【讨论】:

      • 我应该如何创建一个使用您创建的标识符的自定义 tableViewCell myIdentifier ?据我所知,您的代码仍然使用带有标签和详细信息的基本 UITableView 单元格。您能告诉我如何在不使用情节提要的情况下创建具有多个标签的自定义单元格吗?
      • tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "myIdentifier") - 成功了。在这里你可以使用你自己的自定义 UITableviewCell 子类。
      猜你喜欢
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 2011-11-30
      相关资源
      最近更新 更多