yas*_*mir 9 iphone uitableview uiview ios swift
我对快速语言和iOS开发整体都是新手,所以请原谅我缺乏基础知识.以前我尝试并成功实现了多个UITableView自定义部分,方法是创建一个创建TableViewCell的xib文件,然后将其加载到我的主ViewController中,并按以下代码返回:
var customView = NSBundle.mainBundle().loadNibNamed("CustomHeader",owner: self, options: nil)[0] as? UIView
return customView
Run Code Online (Sandbox Code Playgroud)
但是因为我开始得到"没有表格单元被重用的索引路径"我回到绘图板并尝试以编程方式创建UIView并返回它,到目前为止我没有成功但是这是我编码的:
func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView!{
if(section == 0) {
var view = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 50))
var label = UILabel(frame: CGRectMake(0,0, tableView.frame.size.width/2, 20))
label.text="My Details"
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(0, 0, tableView.frame.size.width/2, 20)
button.addTarget(self, action: "visibleRow", forControlEvents:.TouchUpInside)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
button.setTranslatesAutoresizingMaskIntoConstraints(false)
let views = ["label": label,"button":button,"view": view]
var horizontallayoutContraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[label(20)]-60-[button(20)]-10-|", options: NSLayoutFormatOptions(0), metrics: nil, views: views)
view.addConstraints(horizontallayoutContraints)
return view
}
...
Run Code Online (Sandbox Code Playgroud)
你可以看到我正在尝试创建一个布局,我希望我的标签和按钮水平布局,但不知何故逻辑不起作用我尝试禁用视图本身的自动调整约束,但这也没有工作.请帮忙!
rde*_*mar 19
您从未将标签或按钮添加到"查看"中.您的尺寸也没有意义 - 您将标签和按钮的宽度设置为表视图宽度的1/2,但是在您的约束中,您有80个点的空间,因此不能工作.在任何情况下,使用自动布局时都不应设置任何帧.摆脱这些,并为标签或按钮添加垂直约束,并使用布局选项垂直对齐它们.此外,您需要将标签和按钮添加到视图中(并在添加约束之前执行此操作).像这样的东西应该工作,
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if(section == 0) {
var view = UIView() // The width will be the same as the cell, and the height should be set in tableView:heightForRowAtIndexPath:
var label = UILabel()
label.text="My Details"
let button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.addTarget(self, action: "visibleRow:", forControlEvents:.TouchUpInside)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.setTitle("Test Title", forState: .Normal)
let views = ["label": label,"button":button,"view": view]
view.addSubview(label)
view.addSubview(button)
var horizontallayoutContraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[label]-60-[button]-10-|", options: .AlignAllCenterY, metrics: nil, views: views)
view.addConstraints(horizontallayoutContraints)
var verticalLayoutContraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0)
view.addConstraint(verticalLayoutContraint)
return view
}
return nil
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14193 次 |
最近记录: |