【问题标题】:Objective C - Set Label Properties on UIView Subclass from View ControllerObjective C - 从视图控制器设置 UIView 子类的标签属性
【发布时间】:2017-07-23 04:35:19
【问题描述】:

在我的应用程序中,我有一个在 Nib 文件中设计的自定义 Google 地图图钉标记。部分大头针会显示预计到达时间。

这是我加载 Nib 并尝试设置自定义时间的方式:

self.markerPinFromNib = [[[NSBundle mainBundle] loadNibNamed:@"PinWithTimeView" owner:self options:nil] firstObject];
self.markerPinFromNib.estTime.text = @"20";

当我运行这个时,我得到一个错误:

-[UIView estTime]: unrecognized selector sent to instance

PinWithTimeView.h

#import <UIKit/UIKit.h>
@interface PinWithTimeView : UIView

@property (nonatomic, weak) IBOutlet UIImageView *rotateCircle;
@property (nonatomic, strong) IBOutlet UILabel *estTime;

@end

谁能指出我做错了什么?

【问题讨论】:

    标签: ios objective-c uiview


    【解决方案1】:

    在您的 PinWithTimeView.h 中

    @interface PinWithTimeView : UIView
    
    @property (nonatomic, weak) IBOutlet UIImageView *rotateCircle;
    @property (nonatomic, weak) IBOutlet UILabel *estTime;
    -(id)initWithEstTime:(NSString*)time;
    @end
    

    在您的 PinWithTimeView.m 中

    -(id)initWithEstTime:(NSString*)time{
        self = [super init];
        if (self) {
            self = [[[NSBundle mainBundle] loadNibNamed:@"PinWithTimeView" owner:self options:nil] objectAtIndex:0];
            self.estTime.text = time;
    
        }
        return self;
    }
    

    在你的控制器中

    self.markerPinFromNib = [[PinWithTimeView alloc]initWithEstTime:@"20"];
    

    【讨论】:

    • 仍然收到“[UIView estTime]: unrecognized selector sent to instance”...知道为什么吗?
    • 您能否分享一下代码崩溃的行。请使用断点进行调试
    【解决方案2】:

    您应该将实例从 nib 转换为有效的PinWithTimeView。像这样:

    ((PinWithTimeView *)self.markerPinFromNib).estTime.text = @"20";
    

    因为loadNibNamed:owner:options: 将返回一个包含UIView 实例的数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      相关资源
      最近更新 更多