访问 swift 类 之间的变量

Accessing variables between swift classes

使用objective c时我们可以在一个class中创建一个变量,例如:

//  ArticleCell.h


#import <UIKit/UIKit.h>

@class ArticleTitleLabel;

@interface ArticleCell : UITableViewCell
{

    ArticleTitleLabel *_titleLabel;
}

@property (nonatomic, retain) ArticleTitleLabel *titleLabel;

@end

然后在我们的另一个 class 中,我们可以使用导入语句并使用该变量。例如:

但是,当我使用 swift 并声明一个变量时:

class ArticleTableViewCell: UITableViewCell {


    var titleLabel:UILabel!

然后尝试在同一项目中的另一个 class 中使用该变量,我收到以下错误:

我们应该在这里做什么?构造一个strut并有一个全局静态变量或者正确的方法是什么?

当您将单元格出列时,您需要将其转换为 ArticleCell,其中定义了 titleLabel。一种方法是使用 configureCell() 方法扩展 UITableViewCell 并让动态调度调用正确的方法:

  public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
    configureCell(cell, atIndexPath: indexPath)
    return cell
  }

另一种不太通用的方法是:

  public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
    if let articleCell = cell as? ArticleCell {
       articleCell.titleLabel.text = // ...
    }
    else { // other or unexpected cell type }
  }