Chr*_*ris 3 constraints uitableview ios swift
我有一个课程设置如下:
class SettingsController: UITableViewController {
Run Code Online (Sandbox Code Playgroud)
我希望能够向UITableView添加约束,以使表的两边均等(目前是全宽表,因此在iPad上有点难看)。
我已经读到不能将约束添加到UITableViewController
,而必须在UIViewController
类中添加,在上添加UITableView
,然后将约束添加到TableView。
我已经修改了该类,并UITableView
在下一行定义了。所以这是我的前两行:
class SettingsController: UIViewController {
var tableView = UITableView()
Run Code Online (Sandbox Code Playgroud)
再往下看,我有这段代码将TableView附加到UIView
:
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(tableView)
}
Run Code Online (Sandbox Code Playgroud)
该应用程序成功构建,但是在尝试访问该视图时,屏幕为空白,因此我还无法尝试约束部分(如果我还原描述的内容,屏幕会正确显示数据)。
我在该类引用中的许多现有函数都tableView
用于传递数据/设置行数等,但是似乎我做的事情不正确……我缺少什么了吗?
这是一个以编程方式创建表视图并将其添加到“普通”视图的简单示例:
//
// SettingsController.swift
//
// Created by Don Mag on 7/25/17.
//
import UIKit
class SettingsController : UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView : UITableView = {
let t = UITableView()
t.translatesAutoresizingMaskIntoConstraints = false
return t
}()
override func viewDidLoad() {
super.viewDidLoad()
// set a background color so we can easily see the table
self.view.backgroundColor = UIColor.blue
// add the table view to self.view
self.view.addSubview(tableView)
// constrain the table view to 120-pts on the top,
// 32-pts on left, right and bottom (just to demonstrate size/position)
tableView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 32.0).isActive = true
tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 120.0).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -32.0).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -32.0).isActive = true
// set delegate and datasource
tableView.delegate = self
tableView.dataSource = self
// register a defalut cell
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
// Note: because this is NOT a subclassed UITableViewController,
// DataSource and Delegate functions are NOT overridden
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 25
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "\(indexPath)"
return cell
}
// MARK: - Table view delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// etc
}
}
Run Code Online (Sandbox Code Playgroud)
您应该无需编辑即可运行此程序,并获得如下结果:
这是一个非常简单的示例,因此应该很容易看到发生了什么。
如果您已经使您的(我认为是复杂的)Settings UITableViewController
类工作了,那么遵循该框架并将您的框架转换为UIViewController
+ 应当非常简单UITableView-as-subview
。
另外,您可以将现有UITableViewController
的视图加载为子视图控制器,并将其视图(表视图)添加为子视图。
归档时间: |
|
查看次数: |
5226 次 |
最近记录: |