如何从索引中删除UIImageView?
问题描述:
我正在开发一个益智游戏,我添加了所有图像视图到NSMutableArray
但我想删除它的第一阵列,它是在指数0我的代码是:如何从索引中删除UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
var allImageViews : NSMutableArray = NSMutableArray()
var xCen :CGFloat = 53
var yCen :CGFloat = 94
for v in 0...2{
for h in 0...2{
let filename = String(format: "kat_%02i.gif", h+v*3)
let Image = UIImage(named: filename)
let myImageView = UIImageView(image: Image)
myImageView.frame = CGRectMake(0, 0, 106, 189)
myImageView.center = CGPointMake(xCen, yCen)
myImageView.userInteractionEnabled = true
allImageViews.addObject(myImageView)
self.view.addSubview(myImageView)
xCen += 106
}
xCen = 53
yCen += 189
}
allImageViews.removeObjectAtIndex(0)
}
我想我从指数,但其删除对象当我运行项目时仍然出现,所以任何人都可以告诉我如何从超级视图中删除第一个图像?
答
就叫removeFromSuperview
的观点从阵列中取出前:
allImageViews[0].removeFromSuperview()
allImageViews.removeObjectAtIndex(0)
如果您使用的是斯威夫特阵列代替NSMutableArray
,那么你得到更多类型 安全,你可以采取这样的事实优势removeAtIndex()
返回 删除的元素:
override func viewDidLoad() {
super.viewDidLoad()
var allImageViews : [UIImageView] = []
var xCen :CGFloat = 53
var yCen :CGFloat = 94
for v in 0...2{
for h in 0...2{
let filename = String(format: "kat_%02i.gif", h+v*3)
let Image = UIImage(named: filename)
let myImageView = UIImageView(image: Image)
myImageView.frame = CGRectMake(0, 0, 106, 189)
myImageView.center = CGPointMake(xCen, yCen)
myImageView.userInteractionEnabled = true
allImageViews.append(myImageView)
self.view.addSubview(myImageView)
xCen += 106
}
xCen = 53
yCen += 189
}
allImageViews.removeAtIndex(0).removeFromSuperview()
}
您正在添加图像两次。删除其中一个allImageViews.addObject(myImageView) – ytbryan 2014-10-08 06:49:58