简体   繁体   中英

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. 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.

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

There are 2 '>' and I really don't want to create 2 exactly same thing. is there a good way to do it without repeating? Thanks.

Here is my carrotImage property:

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. 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 ()):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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