ios - 如何以只读方式设置 UICollectionViewCell 的属性

标签 ios objective-c uitableview readonly

我有一个 UITableViewCell ProductsCell,我在 nib 中注册了它,然后出队使用它。

我想将它的属性设置为只读。如何做得更好?

代码如下:

@property (nonatomic, strong, readonly) MyProductsVC * targetMyProductsVC;

- (MyProductsVC *)targetMyProductsVC{

    if(!_targetMyProductsVC){
        UIResponder *target = self.nextResponder;
        do {
            target = target.nextResponder;
        } while (![target isKindOfClass: ZBMyProductsVC.self] && target != nil);
        _targetMyProductsVC = (ZBMyProductsVC *)target;

    }
    return _targetMyProductsVC;
}

我无法执行。在 -init,-awakeFromNib 中,因为我使用 UIResponder 找到父 ViewController。

因为在上面的方法中,单元格似乎还没有添加到 super View 上。

如果我这样做,

@property (nonatomic, strong, readonly) MyProductsVC * targetMyProductsVC;

Xcode 报告:

Use of undeclared identifier '_targetMyProductsVC'

设置两个属性即可。一个像上面一样在里面,只需在 getter 方法之外设置另一个只读属性(return 前一个属性。) 有点脏,

有更好的方法吗?

代码可以工作:

@property (nonatomic, strong, readonly) MyProductsVC * targetMyProductsVCReadOnly; 
@property (nonatomic, strong) MyProductsVC * targetMyProductsVC;


- (MyProductsVC *)targetMyProductsVC{

    if(!_targetMyProductsVC){
        UIResponder *target = self.nextResponder;
        do {
            target = target.nextResponder;
        } while (![target isKindOfClass: ZBMyProductsVC.self] && target != nil);
        _targetMyProductsVC = (ZBMyProductsVC *)target;

    }
    return _targetMyProductsVC; }


- (MyProductsVC *)targetMyProductsVCReadOnly{
    return self.targetMyProductsVC; }

最佳答案

因为您正在为 readonly 属性实现自己的属性 getter,这意味着只有一个访问器(即没有 setter),编译器不会自动声明支持变量。来自 Encapsulating Data :

Note: The compiler will automatically synthesize an instance variable in all situations where it’s also synthesizing at least one accessor method. If you implement both a getter and a setter for a readwrite property, or a getter for a readonly property, the compiler will assume that you are taking control over the property implementation and won’t synthesize an instance variable automatically.

If you still need an instance variable, you’ll need to request that one be synthesized:

@synthesize property = _property;  

您在 getter 实现之前插入以上内容以解决未声明的变量错误。

HTH

关于ios - 如何以只读方式设置 UICollectionViewCell 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48063163/

相关文章:

ios - 如何让每个tableview cell呈现不同的detail view controller

ios - 一段时间后设备断开连接且无法获取特征

iOS Framework Delegate 和 IBAction 没有在 Swift 中被调用

ios - 为什么MKMapView的mapView是:viewForOverlay: not called when userlocation is enabled?

ios - 如何防止一个方法一直被调用

ios - 尝试删除 UITableViewCell

在 iOS 上调用 "TypeError: Load Failed"时出现 Javascript "fetch"错误

objective-c - 在 iOS 中没有报摊的应用程序处于非事件状态时在后台下载文件

objective-c - 是否有指南或备忘单可供我引用 Objective C 的所有语法?

ios - 为特定单元格设置 UITableView 单元格类型的更好方法