我正在尝试在 UIView
上的数组中动态排列一组图像数据我希望每个角色有四个,最大角色为 12 个,每个角色有 4 个。这就是问题所在,我可以拆分阵列并将图像均匀地放置在每个人应该出现的位置。例如:
12 张图片
======|=====|======|======|
| | | |
| | | |
======|=====|======|======|
| | | |
| | | |
======|=====|======|======|
| | | |
| | | |
|=====|=====|======|======|
我知道如何排列图像,但是拆分数组就是问题所在。如果我在数组中有 7 张图像,顶部 4 张,底部 3 张或 10 张,即 4、4、2,该怎么办?我不知道该怎么做。这就是为什么我根本没有粘贴任何代码。任何有关拆分和排列数组的帮助将不胜感激。谢谢
最佳答案
将值存储在单个数组中并将该数组用作二维结构的数据源是相当普遍的。可以根据item的index和结构体的宽高得到X和Y的位置。
// number of images across the view
let width = 4;
// number of images down the view
let height = 3;
// index of the image in the array
let index = 10;
// index of the space from the left
// starting with 0
let xLocation = index % width; // 2
// index of the space from the top
// starting with 0
let yLocation = index / width; // 2
下面是一个以元组形式返回值的函数。您需要做的就是遍历数组,它会根据提供的信息返回项目的位置。
func getPosition(width:Int, index:Int) -> (Int,Int) {
return (index % width, index / width);
}
编辑:代码说明
关于arrays - 拆分图像数组并将它们排列在 UIView 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35303371/