【问题标题】:how to create property method in swift如何在swift中创建属性方法
【发布时间】:2023-04-03 19:51:01
【问题描述】:

我在我的类中创建了一个 UITableView 属性,并为它创建了 getter 方法,如下所示:

@interface SideViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) UITableView *table;
@end


@implementation SideViewController
@synthesize selectedIndex;
- (void)viewDidLoad {
  [super viewDidLoad];
  self.view.backgroundColor = [UIColor redColor];
}
- (UITableView*)table {
  if (!_table) {
    CGRect tableFrame = CGRectMake(0,150,230, self.view.frame.size.height-150);
    _table = [[UITableView alloc]initWithFrame:tableFrame style:UITableViewStylePlain];
    _table.scrollEnabled = NO;
    _table.delegate = self;
    _table.dataSource = self;
    _table.showsVerticalScrollIndicator = YES;
    _table.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [_table setBackgroundColor:[UIColor clearColor]];
    _table.separatorStyle = UITableViewCellSeparatorStyleNone;
  }
  return _table;
}

当我打电话给self.table 拿到我的桌子时,我想用 swift 编写这段代码,但我很困惑!!! 请指导我。 这是我的快速代码:

import UIKit

class SideViewController: UIViewController,UITableViewDelegate {

  let table:UITableView = UITableView()

  override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.redColor()

  }


  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }

}

【问题讨论】:

    标签: ios objective-c uitableview swift


    【解决方案1】:

    你可以在swift中使用lazy:

    class SideViewController: UIViewController, UITableViewDelegate {
    
        lazy var table: UITableView = {
            let tableFrame = CGRectMake(0, 150, 230, self.view.frame.size.height - 150)
            let _table = UITableView(frame: tableFrame, style: UITableViewStyle.Plain)
            _table.scrollEnabled = false
            _table.delegate = self
            _table.dataSource = self
            _table.showsVerticalScrollIndicator = true
            _table.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
            _table.backgroundColor = UIColor.clearColor()
            _table.separatorStyle = UITableViewCellSeparatorStyle.None
            return _table
        }()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.view.backgroundColor = UIColor.redColor()
        }
    
    }
    

    【讨论】:

    • 不,就像一个函数,在类本身中
    • 我更新了我的答案,请检查它在你的课堂上的样子
    • 如你所愿,它和通常的 var 一样,唯一的区别是它的内部闭包只计算一次
    猜你喜欢
    • 1970-01-01
    • 2016-03-08
    • 2016-12-26
    • 2021-12-17
    • 2011-04-06
    • 2017-10-09
    • 2014-08-31
    • 2018-08-15
    相关资源
    最近更新 更多