简体   繁体   中英

How To Set Background Image with UIImageView in Swift

I have a tinder clone that I bootstrapped from this github repo ZLSwipeableView .

I want to replace the default background colors with images from my xcassets. So far I've been able to do a pattern image but that's no good, I need to somehow use UIImageView to create a backgroundImage. This is what I have so far:

    let cardView = CardView(frame: swipeableView.bounds)

    if let image = UIImage(named: "Image") {
        cardView.backgroundColor = UIColor(patternImage: image)
    } else {
        print("There was no such image.")
    }

Then the CardView class

    class CardView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {

        // Shadow
        layer.shadowColor = UIColor.blackColor().CGColor
        layer.shadowOpacity = 0.25
        layer.shadowOffset = CGSizeMake(0, 1.5)
        layer.shadowRadius = 4.0
        layer.shouldRasterize = true
        layer.rasterizationScale = UIScreen.mainScreen().scale

        // Corner Radius
        layer.cornerRadius = 10.0;
    }
}

Obviously each card "frame" is set up to handle colors with the UIColor class. How can I convert this CardView frame to a UIImageView object so that I can set backgroundImage?

Try adding a UIImageView as a subview to your CardView

var image:UIImage = UIImage(named: "Image.png")
var labelBackground = UIImageView(frame: CGRectMake(<#CGFloat x#>, <#CGFloat y#>, <#CGFloat width#>, <#CGFloat height#>))
labelBackground = image
cardView.addSubview(labelBackground)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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