Programmatically place partial image over another in UIView using Swift 3

£可爱£侵袭症+ 提交于 2019-12-10 12:27:31

问题


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.

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


回答1:


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.



来源:https://stackoverflow.com/questions/46524174/programmatically-place-partial-image-over-another-in-uiview-using-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!