【发布时间】:2017-06-03 15:45:25
【问题描述】:
我有一个带有海关单元格的 UITableView:ParagraphTableViewCell。
@IBDesignable
class ParagraphTableViewCell: UITableViewCell {
weak var delegate: ParagraphProtocol?
var paragraph:Paragraph!
@IBInspectable @IBOutlet weak var dialogueLabel: UILabel!
@IBInspectable @IBOutlet weak var choice1Button: ChoiceButton!
@IBInspectable @IBOutlet weak var choice2Button: ChoiceButton!
@IBInspectable @IBOutlet weak var choice3Button: ChoiceButton!
}
ChoiceButton 是一个 UIButton 自定义类:
class ChoiceButton: UIButton {
var goToParagraphId: String!
@IBInspectable var text: String? {
didSet {
self.setTitle(text, for: .normal)
print("ChoiceButton didSet viewLabel, viewLabel = \(text!)")
}
}
required init(text: String, goToParagraphId:String) {
self.text = text
self.goToParagraphId = goToParagraphId
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
对于我的项目,我创建了一个对象 Paragraph,其中定义了单元格内容。
class Paragraph: NSObject {
var id:String!
var dialogueLabel: UILabel!
var choice1Button: ChoiceButton!
var choice2Button: ChoiceButton!
var choice3Button: ChoiceButton!
init(dict: NSDictionary) {
self.dialogueLabel = UILabel()
self.dialogueLabel.text = dict["keyLabel"]! as! String
if dict["button1"] != nil {
self.choice1Button=ChoiceButton(text: dict["keyLabel"]! as! String, goToParagraphId: 1)
}
//do the same for the other ChoiceButton
}
为了填充我的 UITableView,我有一个段落对象的 NSMutableArray。 在configureCell函数中,我需要用Paragraph对象的ChoiceButton来设置单元格的ChoiceButton。
func configureCell(tableView: UITableView, cell: ParagraphTableViewCell, atIndexPath indexPath: IndexPath) {
let paragraph = paragraphArray[indexPath.row] as! Paragraph
cell.paragraph = paragraph
//TO SET the ChoiceButton I tried :
cell.choice1Button = paragraph.choice1Button // -> not worked
//TO SET the ChoiceButton I tried also
cell.choice1Button.goToParagraphId = paragraph.choice1Button.goToParagraphId
cell.choice1Button.text = paragraph.choice1Button.text!
// -> but the other properties of UIButton class are not set, as the state of the UIButton
}
我也尝试在 ChoiceButton 类中使用 NSCopying:
func copy(with zone: NSZone? = nil) -> Any {
let copy = ChoiceButton(text: text!, goToParagraphId: goToParagraphId)
return copy
}
我不知道如何在不丢失 UIButton 属性的情况下将单元格中的 ChoiceButton 与段落对象中的 ChoiceButton 链接起来。
【问题讨论】:
-
听起来像是一种不寻常的方法...通常,在典型的表格视图格式中,您的
Paragraph对象将仅包含数据,而不包含 UI 对象。您是否有理由不想简单地用UILabel和三个ChoiceButtons 设计您的单元格,然后使用段落中的 data 分配.text和 .setTitle()对象? -
没有理由,我认为这是个好主意。
-
好的 - 那么我强烈建议不要使用该模型,因为您已经看到了可能遇到的许多问题中的第一个。
-
好的,谢谢你,我会听从你的建议的:)
标签: ios swift uitableview uibutton copy