Skip to main content
 首页 » 操作系统

swift之如何以编程方式将 9 个偶数图像添加到 View |Swift

2024年01月01日31xing901022

我正在努力解决这个问题,希望能找到有关代码的任何帮助。 我正在尝试以编程方式添加 9 个图像 (3x3),它们将覆盖我的整个 UIView。 我的问题是,如何将我的 UIView 分成 9 个偶数图像以覆盖所有图像,并考虑 iPhone 屏幕尺寸之间的差异。 我什至不知道如何开始自定义它,例如:

    firstImage.frame = CGRectMake(?,? ,200,200) 
    secondImage.frame = CGRectMake(?,?, 200,200) 

请您参考如下方法:

您可以将view.frame 分成一个网格,然后在特定位置添加UIImageView 作为 subview 。图片位于 UIImage 数组中。

func create(){ 
        //Divide the screen height and width /3 because 3*3 
        var height = self.view.frame.height/3 
        var width = self.view.frame.width/3 
        //Add your images 
        var imageArray:[UIImage] = [firstImage, secondImage] 
        var count = 0 
        for i in 0...2{ 
            for j in 0...2{ 
                //Add a subview at the position 
                var subview = UIImageView(frame: CGRectMake(width*CGFloat(j), height*CGFloat(i), width, height)) 
                subview.image = imageArray[count] 
                self.view.addSubview(subview) 
                count++ 
 
            } 
        } 
    }