【问题标题】:Custom UIView not showing anything自定义 UIView 不显示任何内容
【发布时间】:2016-10-01 08:27:41
【问题描述】:

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

【问题讨论】:

  • 您正在使用便利初始化程序,但您没有使用便利关键字。

标签: ios swift xcode uiview uiviewcontroller


【解决方案1】:

当您从XibIBOutlet 连接获取自定义视图时,您的自定义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)

        }

【讨论】:

  • 我没有用于自定义视图的 xib。它只是一个快速文件
  • 那你的IBOutlet连接器连接到哪个文件?
  • 在视图控制器的视图中,我添加了一个 UIView 并将它的类设置为 IndicatorView(custom)。并在 viewcontroller 中将此视图设置为 IBOutlet
  • 在这种情况下,“init(frame:CGRect, imageName: String, indicatorValue: String)”方法也不会调用。在 awakeFromNib 方法下实现你的初始化。
  • @Nitish 你不能从笔尖唤醒参数,从笔尖唤醒你只需添加子视图和你的UIView类的IBOutlet来自viewcontroller你可以传递你需要的图像名称在您的UIView 班级中获取一处房产
猜你喜欢
  • 2014-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
  • 2016-03-11
  • 1970-01-01
相关资源
最近更新 更多