所以基本上,我有一个名为 eventImages 的UIImages
数组。
在obj-C中,我声明了它并将其初始化为:
NSArray *eventImages;
eventImages = @[ [UIImage imageNamed:@"lion_dance.jpg"],
[UIImage imageNamed:@"ivan_cheong.jpg"],
[UIImage imageNamed:@"tien_nguyen.jpg"],
[UIImage imageNamed:@"step_up.jpg"],
@[ [UIImage imageNamed:@"dj_happee.jpg"], [UIImage imageNamed:@"adam_cease.jpg"], [UIImage imageNamed:@"ao_dai.jpg"] ],
[UIImage imageNamed:@"california_summer.jpg"],
[UIImage imageNamed:@"question_mark"] ];
如您所见,在第4个索引处,我可以存储内部数组UIImages
。
我想在Swift 2.0中实现这个目标
这是我到目前为止所做的:
var eventImages: [UIImage]?
eventImages = [UIImage(named: "lion_dance.jpg")!,
UIImage(named: "ivan_cheong.jpg")!, UIImage(named: "tien_nguyen.jpg")!,
UIImage(named: "step_up.jpg")!, [UIImage(named: "dj_happee.jpg")!,
UIImage(named: "adam_cease.jpg")!, UIImage(named: "ao_dai.jpg")!],
UIImage(named: "california_summer.jpg")!, UIImage(named: "question_mark")!]
但是,编译器给出了错误:
上下文类型'UIImage'不能与数组文字一起使用
我如何在Swift中实现我在Obj-C中取得的成就?
由于
答案 0 :(得分:0)
你可以这样做:
var eventImages = [UIImage(named: "lion_dance.jpg")!,
UIImage(named: "ivan_cheong.jpg")!, UIImage(named: "tien_nguyen.jpg")!,
UIImage(named: "step_up.jpg")!, [UIImage(named: "dj_happee.jpg")!,
UIImage(named: "adam_cease.jpg")!, UIImage(named: "ao_dai.jpg")!],
UIImage(named: "california_summer.jpg")!, UIImage(named: "question_mark")!]
如果您按UIImage
声明数组类型,则无法添加UIImage
([UIImage]
)数组,因为类型不同。但是,如果你跳过类型声明,Swift会想出来并允许这个数组存在。
我认为数组的类型为NSObject
,然后您可以将其转换为访问图像:
class SomeClass {
var eventImages = [[UIImage()], UIImage(), UIImage(), UIImage(), [UIImage(), UIImage(), UIImage()]]
func doSomething() {
if let singleImage = eventImages[1] as? UIImage {
// Access single image
}
if let imageArray = eventImages[4] as? [UIImage] {
// Access image array
}
}
}
答案 1 :(得分:0)
您可以按照以下步骤将多个图像存储在Swift 2.0阵列中,如下所示
--->首先准备或声明数组对象,如
var eventImages : NSArray = NSArray()
--->现在在数组对象中存储您想要的任何图像,例如
eventImages = ["1.png","2.png","3.png", NSArray(objects: "4.png", "5.png")]
--->现在检查它的数组或字符串是否在数组中并获取图像名称并将其分配给图像视图
if let arr = eventImages.objectAtIndex(2) as? NSString // means it check whether its string
{
self.imgVIew.image = UIImage(named: arr as String)
}
else // if not string then take from array like this
{
self.imgVIew.image = UIImage(named: eventImages.objectAtIndex(3).objectAtIndex(1) as! String)
}
我希望你得到你的图像并将其分配给图像视图...享受..它