2016-10-01 121 views
0

我創建了一個自定義的UIView自定義的UIView不顯示任何

import UIKit 

class IndicatorView: UIView { 

    var image_view_indicator: UIImageView! 
    var label_indicator: UILabel! 

    required init(coder decoder: NSCoder) { 
     super.init(coder: decoder)! 
    } 

    init(frame:CGRect, imageName: String, indicatorValue: String) 
    { 
     super.init(frame: frame) 
     self.frame = frame 
     image_view_indicator = UIImageView(frame: CGRect(x: 0, y: 0, width: 15, height: 15)) 
     image_view_indicator.image = UIImage(named: imageName) 
     self.addSubview(image_view_indicator) 
     self.bringSubviewToFront(image_view_indicator) 

     label_indicator = UILabel(frame: CGRect(x: image_view_indicator.frame.size.width + 3, y: 0, width: 25, height: 15)) 
     label_indicator.text = indicatorValue 
     label_indicator.textColor = UIColor.blackColor() 
     self.addSubview(label_indicator) 
     self.bringSubviewToFront(label_indicator) 
    } 

} 

這是我的電話從UIViewController

view_indicator_friends = IndicatorView(frame: view_indicator_friends.frame, imageName: "friend.png", indicatorValue: "20") 

我交叉檢查IBOutlet連接。他們似乎很好。
但是在自定義視圖中沒有任何顯示。

+0

您正在使用便利初始值設定項,但未使用便捷關鍵字。 – Dasem

回答

0

當你從Xib自定義視圖通過IBOutlet連接,那麼您的自定義init不會調用的,爲什麼你image_view_indicatorlabel_indicator不創建。這就是爲什麼你的自定義視圖不能正確顯示。一種解決方案是在awakeFromNib方法中使用init(frame:CGRect, imageName: String, indicatorValue: String)方法實現您的代碼。

override func awakeFromNib() { 
     let frame = self.frame 
     image_view_indicator = UIImageView(frame: CGRect(x: 0, y: 0, width: 15, height: 15)) 
     image_view_indicator.image = UIImage(named: imageName) 
     self.addSubview(image_view_indicator) 
     self.bringSubviewToFront(image_view_indicator) 

     label_indicator = UILabel(frame: CGRect(x: image_view_indicator.frame.size.width + 3, y: 0, width: 25, height: 15)) 
     label_indicator.text = indicatorValue 
     label_indicator.textColor = UIColor.blackColor() 
     self.addSubview(label_indicator) 
     self.bringSubviewToFront(label_indicator) 

     } 
+0

我沒有自定義視圖的xib。這只是一個迅速的文件 – Nitish

+0

然後你把IBOutlet連接器連接到哪個文件? – iMuzahid

+0

在視圖控制器的視圖中,我添加了一個UIView並將它的類設置爲IndicatorView(自定義)。並將此視圖設置爲視圖控制器中的IBOutlet – Nitish