ios - 如何限制分割 View Controller 左侧的 TableView 的大小?

标签 ios swift uitableview

enter image description here我有一个 UISplitViewController。所以我想看到我的主视图(即 TableView )达到其内容的大小(考虑它只有 3 个元素)。 我尝试使用 self.tableview.contentsize 但没有成功。请帮我找到解决方案。

每个单元格的高度为 44 。 这是我写的代码。

class AccountTableViewController: UITableViewController {
var filterList = [String]()
var selectedIndex = -1

override func viewDidLoad() {
    super.viewDidLoad()
    filterList = ["All Accounts","Business Accounts","Person Accounts"]

    self.tableView.contentSize = CGSize(width: 600, height: 44*3);
}

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

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 3
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("accountCell", forIndexPath: indexPath)

    cell.textLabel?.text = filterList[indexPath.row]
    return cell
}}

最佳答案

我以 Ray Wenderlich 的示例项目 ( https://www.raywenderlich.com/94443/uisplitviewcontroller-tutorial-getting-started ) 作为起点。这就是您在下面的图片中看到的修改内容。

在 Interface Builder 中,首先确保您设置为使用 AutoLayout: enter image description here

然后在原型(prototype)单元格下拖动一个 UIView (我将背景设置为橙色,以便您可以看到它的位置),并将大小设置为您喜欢的大小: enter image description here

我向我们刚刚创建的新 UIView 添加了一些字段,并添加了约束,以便您可以看到它们在运行时根据内容移动。 (您会注意到 Storyboard View Controller 在 IB 中的宽度比运行时大得多。)这是我添加的约束: enter image description here

最后,运行应用程序 - 无需在代码中执行任何操作: enter image description here

一旦你让这个基本部分工作起来,你就可以在代码中配置 View 的大小。如果您愿意,您可以在 IB 中设计 View ,也可以在代码中进行设计 - 无论您喜欢什么。

这是一个表中只有一行的示例:

enter image description here

这是一个表中没有行的示例:

enter image description here

关于ios - 如何限制分割 View Controller 左侧的 TableView 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37551778/

相关文章:

javascript - chrome iOS touchmove 事件不起作用

iOS 本地推送通知覆盖静音/静默模式

uitableview - UITableview header 中的 UITapGesture

ios - 如果 TableViewCell 有大量数据要显示,则在 UITableViewCell 中添加自定义按钮的最佳方式。使用 swift

ios - 如何在 iOS 中使用 Swift 正确检索加速度计数据?

ios - 在不使用全局变量的情况下在多个 swift 类中重用大型未更改数组

ios - 按下主页按钮时如何在 spritekit [SWIFT] 中暂停和重新启动 NSTimer.scheduledTimerWithTimeInterval?

UITableView 和自动高度

ios - 从不正确的线程访问的 Realm - Swift 3

ios - Swift 3 - iOS 10 UITableView 启用 "swipe-to-delete"