Swift 重写类方法

慕弘伟
2023-12-01

我有个Swift的类NFSRacingFinishedHintView继承于Objective-C的类BaseXibView, 声明如下:

#import <UIKit/UIKit.h>

@interface BaseXibView : UIView
+ (id)loadFromXib;
@end

#import "BaseXibView.h"

@implementation <span style="font-family: Arial, Helvetica, sans-serif;">BaseXibView</span>

- (void)dealloc
{
    ITTDINFO(@"%@ is dealloced!", [self class]);
}

+ (id)loadFromXib
{
    return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil] firstObject];
}
@end

</pre><pre code_snippet_id="437407" snippet_file_name="blog_20140728_4_634236" name="code" class="objc">NFSRacingFinishedHintView定义如下:
import UIKit
class NFSRacingFinishedHintView: ITTMaskActivityView {

     var rank:Int!{
        didSet{
            self.rankLabel.text = "\(rank)";
        }
    }
    
    @IBOutlet weak var rankLabel: UILabel!
    
    init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
    }
    
    init(frame: CGRect) {
        super.init(frame: frame)
        // Initialization code
    }

    func setRank(rank:Int) {
        self.rank = rank
    }
    
    override class func loadFromXib() -> AnyObject {
        var objcts:NSArray = NSBundle.mainBundle().loadNibNamed("NFSRacingFinishedHintView", owner: nil, options: nil);
        return objcts.firstObject as NFSRacingFinishedHintView;
    }
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect)
    {
        // Drawing code
    }
    */
}


Swift中类方法使用class关键字,重写用override关键字,由于在Swift中[self class]是不能使用的,所以我在这里直接使用了硬编码。



 类似资料: