ios 自定义UIView背景图像

e0bqpujr  于 2023-02-20  发布在  iOS
关注(0)|答案(3)|浏览(149)

我在我的项目中使用Swift。创建了一个定制的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")!)
    }
}

试图在init()方法中设置背景图像。但是背景图像似乎没有改变。任何建议将不胜感激。谢谢。

kuarbcqp

kuarbcqp1#

在每一个方法中放置一个断点,看看哪个构造函数被调用了。

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

到被调用的构造函数。
在Swift中,一个类必须至少有一个指定的初始化器。你可能需要从init()中删除单词convenience
给予这个:UI颜色(图案图像:UI图像(名称:“背景. png”)!). CG颜色

hgqdbh6s

hgqdbh6s2#

最后我设法解决它。替换self.backgroundColor = UIColor(patternImage: UIImage(named: "BGround.png")!)代码与此:

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

背景图片被添加到了那个视图的图层中。它起作用了。谢谢大家。

sdnqo3pr

sdnqo3pr3#

SWIFT 5

self.contentMode = UIView.ContentMode.scaleToFill
 self.layer.contents = UIImage(named:"bground.png")?.cgImage
 self.bringSubviewToFront(self)
 self.clipsToBounds = true

相关问题