我创建了一个自定义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 :(得分:1)
当您从Xib
到IBOutlet
连接获取自定义视图时,您的自定义init
将不会调用您image_view_indicator
和label_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)
}