这是我的班级
class myCell: UICollectionViewCell {
public var myProp:String = ""
let myControl:UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.Text = myProp
return label
}()
}
我想在创建UI元素时使用myProp
,但编译器说我不能使用myProp
。
或为什么这不正确
class myCell: UICollectionViewCell {
public var myLabel:UILabel = UILabel()
let myControl:UIView = {
let ui = UIView()
myLabel = {
let lbl = UILabel()
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
ui.AddSubView(myLabel)
return ui
}()
}
答案 0 :(得分:0)
这将有效
class CollectionViewCell: UICollectionViewCell {
public var myProp:String = ""
override init(frame: CGRect) {
super.init(frame: frame)
}
func setText() {
let myControl:UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = myProp
return label
}()
self.addSubview(myControl)
}
}
在渲染过程中,cellForRowAtIndex
需要实现此功能,以便在文本中添加子视图。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
cell.myProp = "text"
cell.setText()
return cell
}