如何以编程方式设置 UITableView 的高度

Posted

技术标签:

【中文标题】如何以编程方式设置 UITableView 的高度【英文标题】:How to set height of UITableView programatically 【发布时间】:2017-05-05 08:38:08 【问题描述】:

我有一个表格视图,我想通过代码以编程方式设置表格视图的高度。我该怎么做?

任何帮助将不胜感激。 谢谢你。

【问题讨论】:

你试过设置表格的框架吗 此时应该真的使用自动布局,所以您可能想要搜索,以编程方式向 UITableview 添加约束 【参考方案1】:

ViewDidAppear中使用此代码:

tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: desiredHeight)

【讨论】:

这不会在 Swift 3 中编译。 更新了答案兄弟。谢谢;-)【参考方案2】:

第一步:制作UITableView的outlet

@IBOutlet var tableView: UITableView!

第二步:现在在ViewDidLoad()方法中设置tableView的Frame。

viewDidLoad()

tableView.backgroundColor = UIColor.black
tableView.frame = CGRect(x: 0, y: 0, width: 180, height: 400)

【讨论】:

【参考方案3】:

试试这个代码

  tableView.frame = CGRect(x: 10, y: 10, width: yourwidth, height: yourheight)

【讨论】:

【参考方案4】:

Sivajee Battina 的回答在技术上是正确的,但是,在使用 Swift 3 时不应使用 CGRectMake。这是 Swift 3 的回答:

tableView.frame = CGRect(x: 0, y: 0, width: myWidth, height: myHeight)

【讨论】:

【参考方案5】:

这是一个 Swift 3.1 版本:

//Create table view
let tableView = UITableView();
//Set frame
tableView.frame = CGRect(x: 0, y: 0, width: 100, height:100);
//Add the table to a view as a subview
superView.addSubview(tableView); 
//...

【讨论】:

以上是关于如何以编程方式设置 UITableView 的高度的主要内容,如果未能解决你的问题,请参考以下文章

获取 json 数据后以编程方式设置 UITableViewCell 高度

如何以编程方式更改 UIImageView 的高度?

如何以编程方式设置 UITableView 部分标题(iPhone/iPad)?

如何实现自定尺寸 UITableView?

如何以编程方式设置 UITableView 标头的约束以支持 RTL 和 LTR?

如何以编程方式设置滚动视图高度