Programmatically place partial image over another

2019-06-14 23:59发布

I just started working on Swift last week and i need a suggestion if the following approach is right ways of laying partial image on top of another image.

I have a UIView in which I am creating 3 images programmatically. Left arrow image, middle mobile image and right arrow image as shown below. Can I partially place arrow images 50% on the mobile image?

I have tried:

func setupUI(){
    let mobileImage = UIImage(named: "mobile")
    let arrowImage = UIImage(named: "arrow")

    middleView = UIImageView(frame: CGRect(x: arrowImage!.size.width/2, y:0 , width:mobileImage!.size.width, height:mobileImage!.size.height))
    middleView.image = mobileImage
    middleView.layer.borderWidth = 1.0
    middleView.layer.cornerRadius = 5.0
    self.addSubview(middleView)

    let yForArrow =  mobileImage!.size.height - arrowImage!.size.height
    leftArrow = UIImageView(frame: CGRect(x: 0, y:yForArrow, width:arrowImage!.size.width, height:arrowImage!.size.height))
    leftArrow.image = arrowImage
    self.addSubview(leftArrow)

    let rightArrowX = mobileImage!.size.width
    rightView = UIImageView(frame: CGRect(x: rightArrowX, y:yForArrow, width:arrowImage!.size.width, height:arrowImage!.size.height))
    rightView.image = arrowImage
    self.addSubview(rightView)
}

*At start it was not working, as i forgot to add setupUI() in init method. As shown in answer bellow.

Is setting frame correct way of doing it OR i should be using constraints?

To me it looks bad approach as i am hard coding the numbers in CGRect.

enter image description here

*This image is created in MS paint to show what it should look on iPhone.

1条回答
冷血范
2楼-- · 2019-06-15 00:13

I found the problem i missed adding setupUI() in init method.

SetupUI programatically adds images on UIView. As it was missing so no image was appearing in the iPhone simulator.

override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI() // Code to add images in UIView
    }

But i find it very demotivating that people has down vote the question.

查看更多
登录 后发表回答