簡體   English   中英

UIView:從自定義 XIB 加載導致崩潰

[英]UIView: Loading from custom XIB causing a crash

你好 StackOverflow。

  • 我正在嘗試設置一個UIView ,以便它從 Xcode 中的XIB文件加載自己。

為此,我經歷了以下初始步驟:

  1. 創建了空的UIView子類。
  2. 添加了一個空白的XIB文件。

然后,我將我想要的所有子視圖添加到XIB文件中,並在UIView子類中制作相應的IBOutlet Properties

我觀看此視頻是為了向我展示如何正確連接插座並設置文件所有者。 視頻指導我做以下事情:

  • 不要將 UIView 類設置為XIB的子類。 時間鏈接
  • File's Owner設置為XIBUIView子類:時間鏈接
  • 將 IBOutlet 插入到 UIView 類型的 UIView 類中,以便您的 XIB 文件可以加載到該類中。 時間鏈接
  • 如果您打算在另一個XIB文件中初始化自定義UIView像 (image) 一樣覆蓋initWithCoder
  • 如果您打算在另一個類文件中以編程方式初始化自定義UIView則覆蓋initWithFrame like (image)

酷,我已經完成了所有這些事情,並且選擇以編程方式初始化我的UIView

查看我的UIView子類實現文件

#import "CXHostsTableViewCellContentView.h"

@implementation CXHostsTableViewCellContentView



#pragma mark Custom Initializers

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [[NSBundle mainBundle]loadNibNamed:@"CXHostsTableViewCellContentView" owner:self options:nil];
        [self setBounds:self.view.bounds];
        [self addSubview:self.view];
    }
    return self;
}

-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [[NSBundle mainBundle]loadNibNamed:@"CXHostsTableViewCellContentView" owner:self options:nil];
        [self addSubview:self.view];
    }
    return self;
}

當然,我的頭文件

#import <UIKit/UIKit.h>
#import "CXStyleView.h"

@interface CXHostsTableViewCellContentView : UIView

#pragma mark UIView Properties
@property (strong, nonatomic) IBOutlet UIView *view;

@property (nonatomic,weak)IBOutlet UIView *standardView;

@end

這里還有一張 XIB 文件所有者的圖像另一個從基礎UIView到文件所有者的插座的IBOutlet鏈接。

是的,所以一切看起來都不錯,運行這個應該沒問題吧?

不,每當我初始化這個子視圖並呈現它時,我都會崩潰:

CXHostsTableViewCellContentView *scrollContentView = [[CXHostsTableViewCellContentView alloc]init];

異常截圖

我真的不知道如何解決這個問題,因為我確定我正在正確地遵循所有這些步驟。 我在谷歌上搜索並遇到了這個具有相同症狀的問題,但答案與我使用的代碼相同,並且這個問題的回答相互矛盾。

我不知道此時該做什么,或者是什么導致了崩潰。 我知道,如果我根本沒有連接任何網點,它就可以工作。 但話又說回來,也沒有任何顯示。

我認為當您為 scrollContentView 對象分配內存時會遇到問題。 所以,嘗試用幀分配內存。

在 .m 文件中寫這個

- (void)myAllocation {
              
  //do your stuff
            
}
        
-  (id)initWithFrame:(CGRect)aRect {
           
   self = [super initWithFrame:aRect];
        
   if (self) {
      [self myAllocation];
   }
        
   return self;
        
}
        
 - (id)initWithCoder:(NSCoder*)aDecoder {
           
   self = [super initWithCoder:aDecoder];
   if (self) {
      [self myAllocation];
   }
        
   return self;
        
}

...

CXHostsTableViewCellContentView *scrollContentView = [[CXHostsTableViewCellContentView alloc] initWithFrame:CGRectMake(0, 10, 0, 20)];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM