自定义UIView没有显示任何内容

时间:2016-10-01 08:27:41

标签: ios swift xcode uiview uiviewcontroller

我创建了一个自定义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个连接。他们似乎很好。
但是在自定义视图中没有显示任何内容。

1 个答案:

答案 0 :(得分:1)

当您从XibIBOutlet连接获取自定义视图时,您的自定义init将不会调用您image_view_indicatorlabel_indicator未创建的原因。这就是为什么你的自定义视图没有正确显示。一种解决方案是在init(frame:CGRect, imageName: String, indicatorValue: String)方法的awakeFromNib方法下实现您的代码。

 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)

        }