IOS:使用标签值更改 UIImageView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5830443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IOS: change UIImageView with tag value
提问by cyclingIsBetter
I have 20 UIImageView and i want change their image; but I don't want to create 20 IBOutlet, and I want to use tag value to change the image; I set the tag value in interface builder and after? If I want to change image at Imageview number 15? How can I do?
我有 20 个 UIImageView,我想改变他们的形象;但是我不想创建20个IBOutlet,我想使用标签值来改变图像;我在界面生成器和之后设置标签值?如果我想在 Imageview 编号 15 处更改图像?我能怎么做?
采纳答案by Jake
If you use tags you can identify your tagged view (UIImageView is a subclass of UIView, which has the tag attribute) like this:
如果你使用标签,你可以像这样识别你的标签视图(UIImageView 是 UIView 的子类,它具有 tag 属性):
- (UIView *)viewWithTag:(NSInteger)tag
So if you call this method on your superview (which all the UIImageViews reside in), you should do it like this:
所以如果你在你的超级视图(所有 UIImageViews 驻留)上调用这个方法,你应该这样做:
UIImageView *myImageView = (UIImageView *)[myAwesomeSuperview viewWithTag:15];
(DocumentationI found using Google).
(我使用 Google 找到的文档)。
P.S: if you think it is too much work to add 20 IBOutlets, I recommend you create the UIImageViews programmatically as well. This way you will not need a xib file at all, write a small piece of code and have better maintenance with less effort.
PS:如果您认为添加 20 个 IBOutlets 工作量太大,我建议您也以编程方式创建 UIImageViews。这样你就根本不需要xib文件,编写一小段代码,用更少的精力进行更好的维护。
回答by Gypsa
UIImageView *imageView=(UIImageView *)[self.view viewWithTag:*givetag*];
[imageView setImage:[UIImage imageNamed:@"nameof yourimage"]];
回答by Thyselius
SWIFT, April 2015:
SWIFT,2015 年 4 月:
func createUIImageViews()
{
for i in 0...99
{
var imageView:UIImageView = UIImageView(frame: CGRectMake(CGFloat(0), CGFloat(0), CGFloat(100), CGFloat(100)))
imageView.userInteractionEnabled = true
imageView.tag = i
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "onImageViewTap:"))
self.view.addSubview(imageView)
}
}
func onImageViewTap(sender:UITapGestureRecognizer)
{
println("TAP: \(sender.view!.tag)")
}