简体   繁体   English

自定义 UIView 背景图片

[英]Custom UIView Background image

I'm using Swift for my project.我在我的项目中使用Swift Created a custom UIView class like the following:创建了一个自定义UIView类,如下所示:

class AppBgView: UIView {

    override init (frame : CGRect) {
        super.init(frame : frame)
        //self.isMemberOfClass(<#aClass: AnyClass#>)
    }

    convenience init () {
        self.init(frame:CGRect.zeroRect)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.backgroundColor = UIColor(patternImage: UIImage(named: "BGround.png")!)
    }
}

trying to set background image inside required init() method.试图在所需的init()方法中设置背景图像。 But the background image doesn't seems to change.但背景图像似乎没有改变。 Any suggestion would be appreciated.任何建议将不胜感激。 Thanks.谢谢。

Put a breakpoint in each one of this methods and see which one of the constructors is being called.在每个方法中放置一个断点,看看正在调用哪一个构造函数。 You will need to move the line您将需要移动该行

self.backgroundColor = UIColor(patternImage: UIImage(named: "BGround.png")!)

To the constructor that being called.到被调用的构造函数。

In Swift A class must have at least one designated initializer.在 Swift 中,一个类必须至少有一个指定的初始化程序。 You may need to remove the word convenience from init().您可能需要从 init() 中删除“便利”一词。

Give this one a shot: UIColor(patternImage:UIImage(named: "BGround.png")!).CGColor试一试: UIColor(patternImage:UIImage(named: "BGround.png")!).CGColor

Finally I manage to solve it.最后我设法解决它。 replaced the self.backgroundColor = UIColor(patternImage: UIImage(named: "BGround.png")!) code with this one:用以下self.backgroundColor = UIColor(patternImage: UIImage(named: "BGround.png")!)替换self.backgroundColor = UIColor(patternImage: UIImage(named: "BGround.png")!)代码:

if let image = UIImage(named: "bground.png") {
    self.layer.backgroundColor = UIColor(patternImage: image).CGColor
}

The background image was added to the layer of that view.背景图像已添加到该视图的图层中。 It works.有用。 Thanks everyone.谢谢大家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM