如何在objective-c中实现“swset of swift”?

时间:2022-09-02 08:46:53

Swift (from the book 《iOS Animations by Tutorials:Chapter 12》 released by http://www.raywenderlich.com/):

Swift(来自http://www.raywenderlich.com/发布的“教程的iOS动画:第12章”一书):

let photoLayer = CALayer()

@IBInspectable
  var image: UIImage! {
    didSet {
      photoLayer.contents = image.CGImage
    }
}

How can I implement the above syntax in objective-c? I know only to set the property of photoLayer and image like below:

如何在objective-c中实现上述语法?我知道只设置photoLayer的属性和图像如下:

@property (strong, nonatomic) CALayer *photoLayer;
@property (strong, nonatomic) IBInspectable UIImage *image;

But i do not know how to implement didset{...} parts using objective-c syntax, please help!

但我不知道如何使用objective-c语法实现didset {...}部分,请帮忙!

2 个解决方案

#1


19  

override the setter and implement the setter yourself.

覆盖setter并自己实现setter。

- (void)setImage:(UIImage*)image {
    _image = image;
    photoLayer.contents = image.CGImage
}

#2


2  

Swift needs special language features for this, because of its static nature, one cannot subclass at runtime.

Swift需要特殊的语言功能,因为它具有静态特性,因此无法在运行时进行子类化。

In Objective-C this is not necessary, so you have no language feature for this. You can use key-value observation.

在Objective-C中,这不是必需的,因此您没有语言功能。您可以使用键值观察。

But if the observing instance is the instance whose property changed, you can do it with subclassing as mentioned by @Daij-Djan. (Basically this is what you do in Swift.) Additionally in Objective-C you have the ability to observe the properties of a different instance of a different class.

但是如果观察实例是其属性发生变化的实例,则可以使用@ Daij-Djan提到的子类化来实现。 (基本上这就是你在Swift中所做的。)此外,在Objective-C中,您可以观察不同类的不同实例的属性。

#1


19  

override the setter and implement the setter yourself.

覆盖setter并自己实现setter。

- (void)setImage:(UIImage*)image {
    _image = image;
    photoLayer.contents = image.CGImage
}

#2


2  

Swift needs special language features for this, because of its static nature, one cannot subclass at runtime.

Swift需要特殊的语言功能,因为它具有静态特性,因此无法在运行时进行子类化。

In Objective-C this is not necessary, so you have no language feature for this. You can use key-value observation.

在Objective-C中,这不是必需的,因此您没有语言功能。您可以使用键值观察。

But if the observing instance is the instance whose property changed, you can do it with subclassing as mentioned by @Daij-Djan. (Basically this is what you do in Swift.) Additionally in Objective-C you have the ability to observe the properties of a different instance of a different class.

但是如果观察实例是其属性发生变化的实例,则可以使用@ Daij-Djan提到的子类化来实现。 (基本上这就是你在Swift中所做的。)此外,在Objective-C中,您可以观察不同类的不同实例的属性。