Swift XCode - 故事板中的更改未反映在iPhone模拟器中

时间:2015-08-03 23:07:37

标签: ios swift xcode uitableview button

我正在尝试制作一个简单的UITableView,它在每个单元格的右侧都附加了一个按钮。我在我的故事板中将按钮添加到原型单元格并设置约束,以便AutoLayout接管并将其置于正确的位置。当我在Assistant Editor中预览布局时,一切看起来都很棒。但是,一旦我启动模拟器并转到该视图,按钮就不再存在(单元格为空白)。

当我尝试添加Disclosure Indicator并且没有显示时,我遇到了类似的问题 - 修复它我必须以编程方式添加该附件。故事板不是在不使用代码的情况下帮助进行更改的重点吗?我对此仍然很陌生,并希望得到一些指导。

编辑:根据要求提供一些代码(抱歉):

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = UITableViewCell()

    let addButton = UIButton()

    let menuItem = currentOrder?.getSortedMenuItems()[indexPath.row]
    let itemPrice = "\(currentOrder!.menu[menuItem!]!)"

    cell.textLabel!.text = menuItem! + " - " + itemPrice
    return cell
}

那里的大部分代码都是无关紧要的,但正如你所看到的,我尝试添加一个按钮然后停止,因为我不知道从那里去哪里。我的印象是所有这一切都可以使用故事板完成。

1 个答案:

答案 0 :(得分:1)

您遇到的问题是您没有使用在故事板中创建的单元格。当你打电话

let cell = UITableViewCell()

它创建一个默认样式的单元格。您想要做的是使用您在故事板中创建的单元格。

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

// setup your cells (e.g. update its title)

return cell

}

您应该将“cellWithSwitch”更改为您在故事板中为您的单元格设置的标识符。

您可以通过在故事板中选择单元格的标识符,然后在“属性”检查器中检查信息来找到单元格的标识符:

enter image description here

如果您尚未设置此标识符 - 请将其设置然后再使用它。然后,您在故事板中所做的更改将反映在手机上;)

附加

通常需要对单元格进行子类化以使其更易于使用。这是一个例子:

class MyCell:UITableViewCell {

    @IBOutlet var myButton: UIButton!

}

现在,你还要做其他三件事:

1)在故事板中选择您的单元格,并在Identity检查器中将其类设置为MyCell(这是我发布的图像中的第三个选项卡)

2)打开“连接”检查器(最后一个选项卡)并连接myButton插座

3)修改您的cellForRowAtIndexPathFunction

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellWithSwitch") as! MyCell

// setup your cells (e.g. update its title)

// you can now access your button as cell.myButton

return cell
}
相关问题