使用Swift 3以编程方式将部分图像放在UIView中 [英] Programmatically place partial image over another in UIView using Swift 3
问题描述
我上周刚刚开始研究Swift,如果以下方法是在另一张图像上放置部分图像的正确方法,我需要一个建议。
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.
我有一个UIView,我在其中以编程方式创建3个图像。左箭头图像,中间移动图像和右箭头图像如下所示。我可以在移动图像上部分放置50%的箭头图像吗?
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?
我试过:
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)
}
*开始时它没有用,因为我忘了在init方法中添加setupUI()。如下面的答案所示。
*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?
对我而言,这看起来很糟糕,因为我正在编码CGRect中的数字。
To me it looks bad approach as i am hard coding the numbers in CGRect.
*此图像在MS画图中创建,以显示它在iPhone上的外观。
*This image is created in MS paint to show what it should look on iPhone.
推荐答案
我发现问题我错过了在init方法中添加setupUI()。
I found the problem i missed adding setupUI() in init method.
SetupUI以编程方式在UIView上添加图像。因为它丢失所以iPhone模拟器中没有出现任何图像。
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.
这篇关于使用Swift 3以编程方式将部分图像放在UIView中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!