2016-08-03 78 views
0

我有一個UITableViewCell包含自定義視圖,自定義視圖包含兩個標籤。該視圖分層次喜歡: |---Label 1 XIB---MyTableViewCell---MyView---| |---Label 2 objc自定義視圖與筆尖在tableviewcell上不可見

但運行應用程序,只顯示'MyView',標籤1和標籤2不可見!如果我在viewDidLoad上編寫代碼,請將'MyView'作爲viewController.view的子視圖,標籤1和2出現。希望您能夠幫助我。 enter image description here

+0

在這裏你使用兩個不同的筆尖,一個用於細胞,一個用於myview。我看到你沒有在細胞筆尖上添加標籤。你可以在myview.nib中加入嗎? – SolaWing

+0

@SolaWing是的,標籤屬於MyView.nib。和MyView.nib作爲viewController.subView工作正常 –

+0

所以這是問題。 cell.nib只包含myview,它不包含myview.nib。你需要在cell.nib中添加標籤。或在myview中以編程方式創建標籤 – SolaWing

回答

0

你試過這個嗎?

創建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 
} 
} 

enter image description hereLabel1Label2出口相應的一個。

然後將其添加到自定義tableViewCell爲:(!粉紅色爲高亮)

enter image description hereMy View出口。

自定義單元代碼:

@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 
} 

,你會得到這樣的:

enter image description here

這是什麼喲你在找什麼?


原諒我提供swift代碼,但它沒有太大的不同之處在於objective-c

+0

此解決方案可以正確繪製,但有另一個問題,MyView的自定義類(在Interface Builder設置中)是UIView不是'MyView',所以不能使用outlet屬性label1和label2,類是「MyView」,而不是「UIView」,當調用loadViewFromNib時會導致無限循環。 –

+0

@WilliamSterling我實際上並沒有讓你知道'無限循環',但我編輯了我的答案與網點! – D4ttatraya

+0

非常感謝你@DashAndRest –