无法将专辑插图设置为背景色

Cannot set Album Artwork as background color

我已经使用 MPMediaItemArtwork 拉取了所选歌曲的 album artworkimage 并且我正在尝试将此艺术作品设置为图像 background 类似于 spotify 已经设置好了,但是我不断收到两个错误

Cannot assign a value of type 'UIColor' to a type of value 'UIColor?'

以及

Could not find an overload for 'init' that accepts the supplied arguments

下面是我的代码

func setAlbumCover(){

   var AlbumImage = MPMediaItemArtwork()

    self.view.backgroundColor = UIColor(patternImage: UIImage(named: AlbumImage)!)

    if !UIAccessibilityIsReduceTransparencyEnabled() {
        self.view.backgroundColor = UIColor.clearColor()
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = self.view.bounds
        self.view.addSubview(blurEffectView) //if you have more UIViews on screen, use insertSubview:belowSubview: to place it underneath the lowest view instead

        //add auto layout constraints so that the blur fills the screen upon rotating device
        blurEffectView.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.view.addConstraint(NSLayoutConstraint(item: blurEffectView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        self.view.addConstraint(NSLayoutConstraint(item: blurEffectView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        self.view.addConstraint(NSLayoutConstraint(item: blurEffectView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
        self.view.addConstraint(NSLayoutConstraint(item: blurEffectView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
    } else {
        self.view.backgroundColor = UIColor.whiteColor()
    }

}

我知道我可能犯了一些愚蠢的错误,但我想不通

您正在通过调用需要字符串的 UIImage(named:) 创建 UIImage,并且您正在传递一个 MPMediaItemArtwork 实例。这将编译:

let albumArtwork = MPMediaItemArtwork()
let size = CGSize(width: 250, height: 250)
let image = albumArtwork.imageWithSize(size)
self.view.backgroundColor = UIColor(patternImage: image!)

另请注意,您设置了背景颜色,然后在几行之后更改它,因此图像不会出现:

self.view.backgroundColor = UIColor(patternImage: image!)
if !UIAccessibilityIsReduceTransparencyEnabled() {
    self.view.backgroundColor = UIColor.clearColor()
    // ... some more code ....
} else {
    self.view.backgroundColor = UIColor.whiteColor()
}