将UILabel子类从Objective-C转换为Swift

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将UILabel子类从Objective-C转换为Swift相关的知识,希望对你有一定的参考价值。

我如何将以下子类代码转换为swift 3.1.1我试图转换自己但我得到太多错误

#import <UIKit/UIKit.h>

@interface myTextLabels : UILabel


@property (nonatomic) IBInspectable NSString *overrideFontName;
@property (nonatomic) IBInspectable CGFloat iphoneFontSize;
@property (nonatomic) IBInspectable CGFloat ipadFontSize;
@end

#import "myTextLabels.h"

@implementation myTextLabels

- (void)setOverrideFontName:(NSString *)overrideFontName
{
   if (![_overrideFontName isEqualToString:overrideFontName])
{
    _overrideFontName = overrideFontName;

    self.font = self.font;
   }
}

- (void)setFont:(UIFont *)font
{
   NSString *overrideFontName = self.overrideFontName;
   if (overrideFontName != nil)
  {
    font = [UIFont fontWithName:overrideFontName size:font.pointSize];
  }

   [super setFont:font];
 }

@end  

尝试了各种各样的事情,但我的尝试中有太多错误

import Foundation
import UIKit

class myTextLabel:UILabel{

    @IBInspectable var overrideFontName: String = ""
    @IBInspectable var iphoneFontSize: CGFloat = 0.0
    @IBInspectable var ipadFontSize: CGFloat = 0.0

    func setOverrideFontName(_ overrideFontName: String) {
        if !(self.overrideFontName == overrideFontName) {
            self.overrideFontName = overrideFontName
            font = font
        }
    }

    func setFont(_ font: NSFont!) {
        let overrideFontName: String = self.overrideFontName
        if overrideFontName != nil {
            font = UIFont(name: overrideFontName, size: font.pointSize)
        }
        super.font = font
    }

}
答案

试试吧:

import UIKit

class myTextLabels: UILabel {
@IBInspectable private var _overrideFontName: String = ""
@IBInspectable var overrideFontName: String {
    get {
        return _overrideFontName
    }
    set(overrideFontName) {
        if !(_overrideFontName == overrideFontName) {
            _overrideFontName = overrideFontName
            font = font
        }
    }
}
@IBInspectable var iphoneFontSize: CGFloat = 0.0
@IBInspectable var ipadFontSize: CGFloat = 0.0

override func setFont(_ font: NSFont!) {
    let overrideFontName: String = self.overrideFontName
    if overrideFontName != nil {
        font = UIFont(name: overrideFontName, size: font.pointSize)
    }
    super.font = font
}
}

以上是关于将UILabel子类从Objective-C转换为Swift的主要内容,如果未能解决你的问题,请参考以下文章

以编程方式将所有 UILabel 设置为子类

如何将此方法从 Objective-C 转换为 Swift?

如何将 .hour() 和 .minute() 从 Swift 转换为 Objective-C?

将json调用语法从Objective-C转换为Swift的正确方法是啥?

将方法从 Objective-C 转换为 Swift 时的区别

将utf-8文本转换为UILabel