【问题标题】:UIView strange behaviour with BOOLUIView BOOL 的奇怪行为
【发布时间】:2016-11-18 10:11:08
【问题描述】:

我已经创建了我在 UIViewController 上代表的自定义 UIView。视图显示在屏幕上,但我在该 UIView 实例上设置为 YES 的 BOOL 无法识别。

代码:

UIView 实现:

- (id)initWithFrame:(CGRect)frame{

    self = [super initWithFrame:frame];
    if (self) {
        [self createInterface];
    }
    return self;
}

-(void)createInterface
{
    if (self.isSplash == YES) {
       self.backgroundColor = [UIColor clearColor];
    }
    else {
        self.backgroundColor = DARK_BLUE;
        [self setupTimer];

    }
....

视图控制器:

self.sponsorView = [[SponsorMechanismView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.logo.frame)+10, SCREEN_WIDTH, 100)];
    self.sponsorView.isSplash = YES;

    [self.view addSubview:self.sponsorView];

所以,我将 BOOL 设置为 YES,但在这个 UIView 中它始终为 NO。

【问题讨论】:

  • isSplash设置为true时,createInterface方法已经执行完毕。
  • 知道如何解决这个问题吗?
  • 当然,如果isSplash 发生变化,覆盖isSplash 的设置器并在那里调用createInterface
  • @FabioBerger 请将此添加为答案,以便我接受!

标签: ios objective-c iphone uiview uiviewcontroller


【解决方案1】:

正如法比奥所说,createInterface 已经被执行了。
您可以做的是创建自己的 init 函数。像这样的东西:

- (id)initWithFrame:(CGRect)frame isSplash(BOOL)isSplash
{
    self = [super initWithFrame:frame];
    self.isSplash = isSplash;
    if (self) {
        [self createInterface];
    }
    return self;
}  

函数的调用会是这样的:

self.sponsorView = [[SponsorMechanismView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.logo.frame)+10, SCREEN_WIDTH, 100) isSplash:YES];

【讨论】:

  • 是的,是的,是的!谢谢!这让我了解了很多关于 UIView 的东西!
  • 不客气 :) 请接受答案以供将来参考。
  • 您忘记使用isSplash 参数变量。在if 语句中,您必须在[self createInterface]; 之前分配self.isSplash = isSplash;
  • @JayeshThanki:你说得对。我在您发表评论前几分钟修改了我的代码:)
【解决方案2】:
- (id)initWithFrame:(CGRect)frame AndIsFlash:(BOOL)isFlash{

self = [super initWithFrame:frame];
if (self) {
    [self createInterfaceAndisFlash:isFlash];
}
return self;
}

-(void)createInterfaceAndisFlash:(BOOL)isFlash
{
    if (isFlash == YES) {
        self.backgroundColor = [UIColor clearColor];
    }
    else {
        self.backgroundColor = [UIColor blueColor];
    } 
}

希望你有想法。

【讨论】:

    【解决方案3】:

    如 cmets 中所述:

    当您设置isSplash 时,creatInterface 方法已被执行。 您可以通过覆盖isSplash 的设置器并在那里调用createInterface 来解决此问题。 这里的代码示例:

    - (void)setIsSplash:(BOOL)isSplash
    {
        if (isSplash != _isSplash)
        {
            _isSplash = isSplash;
            [self createInterface];
        }
    }
    

    【讨论】: