简体   繁体   English

Swift中,如何复用UIVIewController中的一个属性

[英]In Swift, how to reuse a property in a UIVIewController

The question is very simple and I bet lots of you guys may had this situation.这个问题很简单,我敢打赌你们中的很多人都可能遇到过这种情况。

I just have a property name called "carrotImage" like a ">" symbol as a property and want to place 2 times in my UIViewController by using view.addSubview.我只有一个名为“carrotImage”的属性名称,如“>”符号作为属性,并且想通过使用 view.addSubview 在我的 UIViewController 中放置 2 次。 I don't actually want to create another new property which has exactly the same image as ">", but I'm thinking that if I really do view.addSubview(carrotImage) 2 times but in different places, and apply SnapKit or built-in autolayouts on them respectively, it would affect the other one.我实际上并不想创建另一个与“>”具有完全相同图像的新属性,但我在想,如果我真的在不同的地方执行 view.addSubview(carrotImage) 2 次,并应用 SnapKit 或构建-分别在它们的自动布局中,它会影响另一个。

As you can see the image:如您所见: 在此处输入图像描述

There are 2 '>' and I really don't want to create 2 exactly same thing.有 2 个“>”,我真的不想创建 2 个完全相同的东西。 is there a good way to do it without repeating?有没有不重复的好方法? Thanks.谢谢。

Here is my carrotImage property:这是我的 carrotImage 属性:

var carrotImage: UIImageView = {
    let imageView = UIImageView()
    imageView.image = UIImage(systemName: "arrowtriangle.right.fill")
    imageView.tintColor = .lightGray
    return imageView
}()

For your use case, you do have to have 2 separate UIImageViews.对于您的用例,您必须有 2 个单独的 UIImageView。 However, they have the same image and properties, so you can reuse the code.但是,它们具有相同的图像和属性,因此您可以重用代码。 If you do not need to later reference carrotImage, you can just make it computed variable like this (remove = and ()):如果您以后不需要引用 carrotImage,您可以像这样将其设为计算变量(删除 = 和 ()):

var carrotImage: UIImageView {
    let imageView = UIImageView()
    imageView.image = UIImage(systemName: "arrowtriangle.right.fill")
    imageView.tintColor = .lightGray
    return imageView
}

This way you can reuse the same code to create new UIImageView with arrowtriangle.right.fill where you need.通过这种方式,您可以在需要的地方使用 arrowtriangle.right.fill 重用相同的代码来创建新的 UIImageView。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM