我有一個UITableViewCell包含自定義視圖,自定義視圖包含兩個標籤。該視圖分層次喜歡: |---Label 1 XIB---MyTableViewCell---MyView---| |---Label 2
objc自定義視圖與筆尖在tableviewcell上不可見
但運行應用程序,只顯示'MyView',標籤1和標籤2不可見!如果我在viewDidLoad上編寫代碼,請將'MyView'作爲viewController.view的子視圖,標籤1和2出現。希望您能夠幫助我。
我有一個UITableViewCell包含自定義視圖,自定義視圖包含兩個標籤。該視圖分層次喜歡: |---Label 1 XIB---MyTableViewCell---MyView---| |---Label 2
objc自定義視圖與筆尖在tableviewcell上不可見
但運行應用程序,只顯示'MyView',標籤1和標籤2不可見!如果我在viewDidLoad上編寫代碼,請將'MyView'作爲viewController.view的子視圖,標籤1和2出現。希望您能夠幫助我。
你試過這個嗎?
創建MyView
這樣的:
class MyView: UIView {
@IBOutlet weak var _label1: UILabel!
@IBOutlet weak var _label2: UILabel!
// Our custom view from the XIB file
var view: UIView!
//MARK: - Setup -
private func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
addSubview(view)
}
private func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "MyView", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
override func awakeFromNib() {
super.awakeFromNib()
}
func setLabeles(lbl1: String, lbl2: String) {
_label1!.text = lbl1
_label2!.text = lbl2
}
}
然後將其添加到自定義tableViewCell
爲:(!粉紅色爲高亮)
自定義單元代碼:
@IBOutlet weak var _myView: MyView!
class func identifier() -> String {
return "CustomTableViewCellId"
}
class func nib() -> UINib {
let nib = UINib(nibName: "CustomTableViewCell", bundle: NSBundle.mainBundle())
return nib
}
//MARK: Public Methods
func setCellIndexLabel(index: Int) {
_myView!.setLabeles("lbl1: \(index)", lbl2: "lbl2: \(index)")
}
那麼就沒有必要做一些額外的東西在表視圖,只是做: 在viewDidLoad()
-
tableView!.registerNib(CustomTableViewCell.nib(), forCellReuseIdentifier: CustomTableViewCell.identifier())
//then
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Configure the cell...
let cell = tableView.dequeueReusableCellWithIdentifier(CustomTableViewCell.identifier(), forIndexPath: indexPath) as! CustomTableViewCell
cell.setCellIndexLabel(indexPath.row)
return cell
}
,你會得到這樣的:
這是什麼喲你在找什麼?
原諒我提供swift
代碼,但它沒有太大的不同之處在於objective-c
!
此解決方案可以正確繪製,但有另一個問題,MyView的自定義類(在Interface Builder設置中)是UIView不是'MyView',所以不能使用outlet屬性label1和label2,類是「MyView」,而不是「UIView」,當調用loadViewFromNib時會導致無限循環。 –
@WilliamSterling我實際上並沒有讓你知道'無限循環',但我編輯了我的答案與網點! – D4ttatraya
非常感謝你@DashAndRest –
在這裏你使用兩個不同的筆尖,一個用於細胞,一個用於myview。我看到你沒有在細胞筆尖上添加標籤。你可以在myview.nib中加入嗎? – SolaWing
@SolaWing是的,標籤屬於MyView.nib。和MyView.nib作爲viewController.subView工作正常 –
所以這是問題。 cell.nib只包含myview,它不包含myview.nib。你需要在cell.nib中添加標籤。或在myview中以編程方式創建標籤 – SolaWing