Xib ファイルからカスタム UITableViewCell をロードするにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/540345

質問

質問は簡単です:カスタムをロードするにはどうすればよいですか UITableViewCell Xibファイルから?これにより、Interface Builder を使用してセルを設計できるようになります。メモリ管理の問題により、答えは明らかに単純ではありません。 このスレッド この問題について言及し、解決策を提案していますが、NDA リリース前であり、コードがありません。ここにあります 長い糸 決定的な答えを提供せずに問題を議論します。

私が使用したコードは次のとおりです。

static NSString *CellIdentifier = @"MyCellIdentifier";

MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
    cell = (MyCell *)[nib objectAtIndex:0];
}

このコードを使用するには、次の新しいサブクラスである MyCell.m/.h を作成します。 UITableViewCell そして追加します IBOutlets 必要なコンポーネントを選択します。次に、新しい「空の XIB」ファイルを作成します。IB で Xib ファイルを開き、 UITableViewCell オブジェクトを作成し、その識別子を「MyCellIdentifier」に設定し、そのクラスを MyCell に設定して、コンポーネントを追加します。最後に接続します。 IBOutlets コンポーネントに。IB でファイルの所有者を設定していないことに注意してください。

他のメソッドでは、ファイルの所有者を設定することを推奨し、Xib が追加のファクトリ クラスを介してロードされていない場合にメモリ リークが発生すると警告します。上記を [Instruments/Leaks] でテストしましたが、メモリ リークは見られませんでした。

それでは、Xib からセルをロードする標準的な方法は何でしょうか?ファイルの所有者を設定しますか?工場は必要ですか?もしそうなら、ファクトリのコードはどのようなものですか?複数の解決策がある場合は、それぞれの長所と短所を明確にしましょう。

役に立ちましたか?

解決

ここでは二つの方法の 元の著者によると、IBエンジニア.

の実際のポスト。う方法#2というより簡単になります。

法#1:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BDCustomCell"];
    if (cell == nil) {
        // Create a temporary UIViewController to instantiate the custom cell.
        UIViewController *temporaryController = [[UIViewController alloc] initWithNibName:@"BDCustomCell" bundle:nil];
        // Grab a pointer to the custom cell.
        cell = (BDCustomCell *)temporaryController.view;
        [[cell retain] autorelease];
        // Release the temporary UIViewController.
        [temporaryController release];
    }

    return cell;
}

法#2:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BDCustomCell"];
    if (cell == nil) {
        // Load the top-level objects from the custom cell XIB.
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"BDCustomCell" owner:self options:nil];
        // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
        cell = [topLevelObjects objectAtIndex:0];
    }

    return cell;
}

更新(2014年度): 法#2の有効期限が切れていないことではありません書かなくなった。で使用するには 公式docs 現在では取り除いて賛同のふ.

掲載作例Github:
https://github.com/bentford/NibTableCellExample

編集のための迅速な4.2

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    self.tblContacts.register(UINib(nibName: CellNames.ContactsCell, bundle: nil), forCellReuseIdentifier: MyIdentifier)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: MyIdentifier, for: indexPath) as! ContactsCell

    return cell
}

他のヒント

右のソリューションはこれです:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UINib *nib = [UINib nibWithNibName:@"ItemCell" bundle:nil];
    [[self tableView] registerNib:nib forCellReuseIdentifier:@"ItemCell"];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Create an instance of ItemCell
    PointsItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ItemCell"];

    return cell;
}

登録

後iOS7では、この処理を簡素化ダ(迅速3.0):

// For registering nib files
tableView.register(UINib(nibName: "MyCell", bundle: Bundle.main), forCellReuseIdentifier: "cell")

// For registering classes
tableView.register(MyCellClass.self, forCellReuseIdentifier: "cell")

(注意 ことも可能になり細胞の .xib または .stroyboard ファイルとして試作品の細胞。が必要な場合は添付のクラスをを選択することができ、細胞試作品の追加に対応するクラスでなければな子孫 UITableViewCell, ますか?

Dequeue

以降、dequeued用迅速3.0):

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = "Hello"

    return cell
}

のの違いによるこの新しい方法なdequeuesの細胞でも作成する場合のexistantすることと思い if (cell == nil) 理を主に取り上げ、その犯罪心理に細胞を利用している例です。

(警告) tableView.dequeueReusableCell(withIdentifier:for:) の新たな行動、お問い合わせいただいた場合はなし indexPath: また、古い行動を確認する必要があるため nil およびインスタンスで自分の通知を UITableViewCell? 戻り値です。

if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MyCellClass
{
    // Cell be casted properly
    cell.myCustomProperty = true
}
else
{
    // Wrong type? Wrong identifier?
}

もちろんの種類に関連しているクラスの細胞の一つで定義されます。xibファイルの UITableViewCell サブクラス、または、その他の登録方法です。

構成

理想的には、細胞て構成され、外観およびコンテンツの位置などのラベルと画像ビュー)にご登録いただいたての cellForRowAtIndexPath 方法を使って記入します。

class MyCell : UITableViewCell
{
    // Can be either created manually, or loaded from a nib with prototypes
    @IBOutlet weak var labelSomething : UILabel? = nil
}

class MasterViewController: UITableViewController 
{
    var data = ["Hello", "World", "Kinda", "Cliche", "Though"]

    // Register
    override func viewDidLoad()
    {
        super.viewDidLoad()

        tableView.register(MyCell.self, forCellReuseIdentifier: "mycell")
        // or the nib alternative
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return data.count
    }

    // Dequeue
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! MyCell

        cell.labelSomething?.text = data[indexPath.row]

        return cell
    }
}

もちろん、これは全てご用意ObjC同じ名です。

ショーンCraverの答えを取り、少しそれをクリーンアップします。

BBCell.hます:

#import <UIKit/UIKit.h>

@interface BBCell : UITableViewCell {
}

+ (BBCell *)cellFromNibNamed:(NSString *)nibName;

@end

BBCell.mます:

#import "BBCell.h"

@implementation BBCell

+ (BBCell *)cellFromNibNamed:(NSString *)nibName {
    NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:NULL];
    NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
    BBCell *customCell = nil;
    NSObject* nibItem = nil;
    while ((nibItem = [nibEnumerator nextObject]) != nil) {
        if ([nibItem isKindOfClass:[BBCell class]]) {
            customCell = (BBCell *)nibItem;
            break; // we have a winner
        }
    }
    return customCell;
}

@end

私はBBCellのすべての私のUITableViewCellのサブクラスを作り、その後、標準を置き換える

cell = [[[BBDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BBDetailCell"] autorelease];

cell = (BBDetailCell *)[BBDetailCell cellFromNibNamed:@"BBDetailCell"];

使用したbentfordの 法#2:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BDCustomCell"];
    if (cell == nil) {
        // Load the top-level objects from the custom cell XIB.
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"BDCustomCell" owner:self options:nil];
        // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
        cell = [topLevelObjects objectAtIndex:0];
    }

    return cell;
}

この作品が見つ ファイルのオーナー ご注UITableViewCell.xibファイルです。

owner:selfloadNibNamed 決設定する UITableViewController ファイルのオーナーのご UITableViewCell.

場合はドラッグ&ドロップ、ヘッダファイルIB設定行動や店舗で設としてファイルのオーナーによるデフォルトです。

loadNibNamed:owner:options, アップルのコードのみのプロパティを設定します。ご UITableViewController, その場所にあります。がん特性の定義にあり、エラーについて キー値の符号化対応:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason:     '[<MyUITableViewController 0x6a383b0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key myLabel.'

場合はイベントが動くしょんNSInvalidArgumentException:

-[MyUITableViewController switchValueDidChange:]: unrecognized selector sent to instance 0x8e9acd0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyUITableViewController switchValueDidChange:]: unrecognized selector sent to instance 0x8e9acd0'
*** First throw call stack:
(0x1903052 0x15eed0a 0x1904ced 0x1869f00 0x1869ce2 0x1904ec9 0x5885c2 0x58855a 0x62db76 0x62e03f 0x77fa6c 0x24e86d 0x18d7966 0x18d7407 0x183a7c0 0x1839db4 0x1839ccb 0x1f8b879 0x1f8b93e 0x585a9b 0xb904d 0x2c75)
terminate called throwing an exceptionCurrent language:  auto; currently objective-c

簡単に回避策がポイントをインターフェースビルダーに接続した場合の UITableViewCell の代わりにファイルのオーナー:

  1. 右クリックしてファイルのオーナーダのリストからの接続
  2. 受画面キャプチャーとのコマンド-Shift-4ドラッグ選択し、撮影)
  3. xの接続からファイルのオーナー
  4. 右クリックしUITableCellのオブジェクト階層と再追加します。

私たらないようにこれらの回答になりますので、よりシンプルで、これまでで最も簡潔な方います。

1.をXibのインターフェイスをビルダーとしてあります。

  • 設定ファイルのオーナーはクラスNSObject
  • 追加UITableViewCellをセットクラスMyTableViewCellSubclass--がIBクラッシュ(そXcode>4現在のところのように)を使用UIViewののインタフェースXcode4だいていけ
  • レイアウトsubviewsこの細胞および添付IBOutlet接続を@インターフェース。hいます。m(.mは私の好み)

2.おUIViewControllerはUITableViewControllerサブクラス

@implementation ViewController

static NSString *cellIdentifier = @"MyCellIdentier";

- (void) viewDidLoad {

    ...
    [self.tableView registerNib:[UINib nibWithNibName:@"MyTableViewCellSubclass" bundle:nil] forCellReuseIdentifier:cellIdentifier];
}

- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyTableViewCellSubclass *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    ...

    return cell;
}

3.おMyTableViewCellSubclass

- (id) initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        ...
    }

    return self;
}

あなたはインスペクタ内の識別子を設定していることを確認し、細胞を作るためにInterface Builderを使用している場合。そして、dequeueReusableCellWithIdentifierを呼び出すときに、それは同じだと確認します。

私が誤って表重いプロジェクトにいくつかの識別子を設定するのを忘れ、そして性能変化は夜と昼のようだった。

XIB から UITableViewCell をロードすると、多くのコードが節約されますが、通常はスクロール速度が遅くなります (実際には、XIB ではなく、UIView の過度の使用が原因です)。

これをご覧になることをお勧めします。 リンクリファレンス

ここで私はXIBsのうち、カスタムセルを作成するために使用してきたクラスメソッドです

+ (CustomCell*) createNewCustomCellFromNib {

    NSArray* nibContents = [[NSBundle mainBundle]
                            loadNibNamed:@"CustomCell" owner:self options:NULL];

    NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
    CustomCell *customCell= nil;
    NSObject* nibItem = nil;

    while ( (nibItem = [nibEnumerator nextObject]) != nil) {

        if ( [nibItem isKindOfClass: [CustomCell class]]) {
            customCell = (CustomCell*) nibItem;

            if ([customCell.reuseIdentifier isEqualToString: @"CustomCell"]) {
                break; // we have a winner
            }
            else
                fuelEntryCell = nil;
        }
    }
    return customCell;
}

次に、XIBでは、私はクラス名を設定し、識別子を再利用します。その後、私はちょうどの代わりに、私のビューコントローラでそのメソッドを呼び出すことができます。

[[UITableViewCell] alloc] initWithFrame:]

これは十分に速くたくさんだ、と私の出荷アプリケーションの2で使用されています。あなたが唯一の右のタイプであるXIBのうちビューをつかむために保証しているので、それは[nib objectAtIndex:0]を呼び出すよりも信頼性だ、とステファンBurlotの例よりも、私の心の中で、少なくとも、より信頼性の高います。

正解はこれです。

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"CustomCell"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
    return cell; 
    }

NIBをリロードすることは高価です。あなたはセルを必要とするとき、より良い、一度それをロードするために、そしてオブジェクトをインスタンス化します。あなたがこの方法を使用して、ペン先にも、複数のセルをUIImageViewsなどを追加することもできます(Appleの「registerNIB」iOS5をのみ1つのトップレベルのオブジェクトを可能に - バグ10580062 "iOS5をのtableView registerNib:過度に制限"

あなたは、のviewDidLoad私は初期のようにまたはで(一度NIBで読む - - 。私のコードは以下の通りですので、

。何でもその時から、あなたは、あなたが必要なものを選択するオブジェクトにペン先をインスタンスこれはよりもはるかに効率的です何度もペン先をロードします。

static UINib *cellNib;

+ (void)initialize
{
    if(self == [ImageManager class]) {
        cellNib = [UINib nibWithNibName:@"ImageManagerCell" bundle:nil];
        assert(cellNib);
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"TheCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if(cell == nil) {
        NSArray *topLevelItems = [cellNib instantiateWithOwner:nil options:nil];
        NSUInteger idx = [topLevelItems indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop)
                            {
                                UITableViewCell *cell = (UITableViewCell *)obj;
                                return [cell isKindOfClass:[UITableViewCell class]] && [cell.reuseIdentifier isEqualToString:cellID];
                            } ];
        assert(idx != NSNotFound);
        cell = [topLevelItems objectAtIndex:idx];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"Howdie %d", indexPath.row];

    return cell;
}

これをチェック - http://eppz.eu/blog/custom-uitableview-cell

: - / のコントローラの実装に1行を終わる小さなクラスを使用して、本当に便利な方法
-(UITableViewCell*)tableView:(UITableView*) tableView cellForRowAtIndexPath:(NSIndexPath*) indexPath
{
    return [TCItemCell cellForTableView:tableView
                          atIndexPath:indexPath
                      withModelSource:self];
}

ここに画像の説明を入力します

それを行うための正しい方法はUITableViewCellのサブクラス実装、ヘッダ、及びXIBを作成することです。 XIBで任意のビューを削除し、ちょうどテーブルセルを追加します。 UITableViewCellのサブクラスの名前としてクラスを設定します。ファイルの所有者のために、それのUITableViewControllerのサブクラスのクラス名にします。 tableViewCellコンセントを使用して、細胞へのファイルの所有者を接続します。

ヘッダ・ファイルに

UITableViewCell *_tableViewCell;
@property (assign) IBOutlet UITableViewCell *tableViewCell;

実装ファイルでます:

@synthesize tableViewCell = _tableViewCell;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *kCellIdentifier = @"reusableCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:kCellIdentifier owner:self options:nil];
        cell = _tableViewCell;
        self.tableViewCell = nil;
    }

    return cell;
}

私はこれのためにやっていることは、あなたのコントローラクラスでIBOutlet UITableViewCell *cellを宣言しています。 次いで、上記宣言セルにNSBundle loadNibNamedを供給しますUITableViewCellクラスのメソッドを呼び出す。

XIBのために私は空のXIBを作成し、必要に応じてそれをセットアップすることができIBでUITableViewCellオブジェクトを追加します。このビューは、コントローラクラスの細胞IBOutletに接続されている。

- (UITableViewCell *)tableView:(UITableView *)table
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@ loading RTEditableCell.xib", [self description] );

    static NSString *MyIdentifier = @"editableCellIdentifier";
    cell = [table dequeueReusableCellWithIdentifier:MyIdentifier];

    if(cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"RTEditableCell"
                                      owner:self
                                    options:nil];
    }

    return cell;
}

<のhref = "http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSBundle_AppKitAdditions/Reference/Reference.html#//apple_ref/doc/uid/20000401-CJBHHDFC" のrel = "nofollowをnoreferrer"> NSBundle添加loadNibNamed(ADCログイン)の

cocoawithlove.com記事私は(電話番号のサンプルを取得からコンセプトを調達アプリ)

まずカスタムセルファイル#import "CustomCell.h"をインポートして言及した以下のようにデリゲートメソッドを変更します。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *simpleTableIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}         

     return cell;
}
  1. 自分でカスタマイズクラス AbcViewCell サブクラスから UITableViewCell (クラスファイル名をペン先のファイル名は同じです)

  2. この拡張機能のクラス方法です。

    extension UITableViewCell {
        class func fromNib<T : UITableViewCell>() -> T {
            return Bundle.main.loadNibNamed(String(describing: T.self), owner: nil, options: nil)?[0] as! T
        }
    }
    
  3. して使用します。

    let cell: AbcViewCell = UITableViewCell.fromNib()

のスイフト4.2するとXcode 10

私は3つのXIBセルファイルを持っている。

のviewDidLoadで、このようなあなたのXIBファイルを登録...

これは最初のアプローチである

tableView.register(UINib.init(nibName: "XIBCell", bundle: nil), forCellReuseIdentifier: "cell1")
tableView.register(UINib.init(nibName: "XIBCell2", bundle: nil), forCellReuseIdentifier: "cell2")
//tableView.register(UINib.init(nibName: "XIBCell3", bundle: nil), forCellReuseIdentifier: "cell3")

第二のアプローチは、直接の cellForRowAt indexPathでXIBファイルを登録します。

これは私のテーブルビューのデリゲート機能です。

//MARK: - Tableview delegates
override func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return 6
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //This is first approach
    if indexPath.row == 0 {//Load first XIB cell
        let placeCell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! XIBCell
        return placeCell
    //Second approach
    } else if indexPath.row == 5 {//Load XIB cell3
        var cell = tableView.dequeueReusableCell(withIdentifier:"cell3") as? XIBCell3
        if cell == nil{
            let arrNib:Array = Bundle.main.loadNibNamed("XIBCell3",owner: self, options: nil)!
            cell = arrNib.first as? XIBCell3
        }

        //ADD action to XIB cell button
        cell?.btn.tag = indexPath.row//Add tag to button
        cell?.btn.addTarget(self, action: #selector(self.bookbtn1(_:)), for: .touchUpInside);//selector

        return cell!
    //This is first approach
    } else {//Load XIB cell2
        let placeCell = tableView.dequeueReusableCell(withIdentifier: "cell2") as! XIBCell2

        return placeCell
    }

}

そのための私の方法は次のとおりです。 XIB ファイルからカスタム UITableViewCell をロード…さらに別の方法

アイデアは、次の SampleCell サブクラスを作成することです。 UITableViewCell とともに IBOutlet UIView *content プロパティと、コードから設定する必要がある各カスタム サブビューのプロパティ。次に、SampleCell.xib ファイルを作成します。この nib ファイルで、ファイル所有者を SampleCell に変更します。コンテンツを追加する UIView ニーズに合わせたサイズ。必要なすべてのサブビュー (ラベル、画像ビュー、ボタンなど) を追加して構成します。最後に、コンテンツ ビューとサブビューをファイル所有者にリンクします。

ここには普遍性のあるアプローチを登録するための細胞 UITableView:

protocol Reusable {
    static var reuseID: String { get }
}

extension Reusable {
    static var reuseID: String {
        return String(describing: self)
    }
}

extension UITableViewCell: Reusable { }

extension UITableView {

func register<T: UITableViewCell>(cellClass: T.Type = T.self) {
    let bundle = Bundle(for: cellClass.self)
    if bundle.path(forResource: cellClass.reuseID, ofType: "nib") != nil {
        let nib = UINib(nibName: cellClass.reuseID, bundle: bundle)
        register(nib, forCellReuseIdentifier: cellClass.reuseID)
    } else {
        register(cellClass.self, forCellReuseIdentifier: cellClass.reuseID)
    }
}

説明:

  1. Reusable プロトコルを生成し細胞を利用して次のように書き換えられ、そのクラスの名前です。ただくにはコン cell ID == class name == nib name.
  2. UITableViewCell に適合して Reusable プロトコルです。
  3. UITableView 延長講演概要集の違いを登録す細胞を介ペン先されました。

使用例:

override func viewDidLoad() {
    super.viewDidLoad()
    let tableView = UITableView()
    let cellClasses: [UITableViewCell.Type] = [PostCell.self, ProfileCell.self, CommentCell.self]
    cellClasses.forEach(tableView.register)
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: PostCell.self.reuseID) as? PostCell
    ...
    return cell
}

あまりないと思いますがあればお知ら標準の方が、ここでの私の方法:

  • をxibのためのViewController
  • 設定ファイルのオーナークラスUIViewController
  • 削除とデニースザメネースパークに追加UITableViewCell
  • セットのクラスのUITableViewCellをカスタムクラス
  • セットの識別子のUITableViewCell
  • セットのアウトレットのビューコントローラビューをUITableViewCell

このコード:

MyCustomViewCell *cell = (MyCustomViewCell *)[_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
  UIViewController* c = [[UIViewController alloc] initWithNibName:CellIdentifier bundle:nil];
  cell = (MyCustomViewCell *)c.view;
  [c release];
}

おとえば、

[nib objectAtIndex:0]

ある休憩場合はAppleの変更、項目の順番xib.

 NSString *CellIdentifier = [NSString stringWithFormat:@"cell %ld %ld",(long)indexPath.row,(long)indexPath.section];


    NewsFeedCell *cell = (NewsFeedCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell=nil;

    if (cell == nil)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"NewsFeedCell" owner:nil options:nil];

        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[NewsFeedCell class]])
            {
                cell = (NewsFeedCell *)currentObject;
                break;
            }
        }
}
return cell;

この拡張はXcode7のbeta6が必要です。

extension NSBundle {
    enum LoadViewError: ErrorType {
        case ExpectedXibToExistButGotNil
        case ExpectedXibToContainJustOneButGotDifferentNumberOfObjects
        case XibReturnedWrongType
    }

    func loadView<T>(name: String) throws -> T {
        let topLevelObjects: [AnyObject]! = loadNibNamed(name, owner: self, options: nil)
        if topLevelObjects == nil {
            throw LoadViewError.ExpectedXibToExistButGotNil
        }
        if topLevelObjects.count != 1 {
            throw LoadViewError.ExpectedXibToContainJustOneButGotDifferentNumberOfObjects
        }
        let firstObject: AnyObject! = topLevelObjects.first
        guard let result = firstObject as? T else {
            throw LoadViewError.XibReturnedWrongType
        }
        return result
    }
}

ちょうど1カスタムUITableViewCellのが含まれているXIBファイルを作成します。

それをロードします。

let cell: BacteriaCell = try NSBundle.mainBundle().loadView("BacteriaCell")
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cellReuseIdentifier = "collabCell"
            var cell:collabCell! = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as? collabCell
            if cell == nil {
                tableView.register(UINib(nibName: "collabCell", bundle: nil), forCellReuseIdentifier: cellReuseIdentifier)
                cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! collabCell!
            }


            return cell

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top