使用swift的不同字体大小的时间格式

使用swift的不同字体大小的时间格式,swift,Swift,我想知道是否有人能帮忙。我正在创建一个基本的iOS应用程序来显示时间,但是我无法为时间标签设置不同的字体大小。基本上,我需要的时间HH(小时):毫米(分钟)一个不同的大小字体的SS(秒) 我一直在看属性文本,但仍然无法得出一些结果 问候。您可以扩展NSMutableAttributedString: extension NSMutableAttributedString { @discardableResult func resize(_ text: String, _ size: CG

我想知道是否有人能帮忙。我正在创建一个基本的iOS应用程序来显示时间,但是我无法为时间标签设置不同的字体大小。基本上,我需要的时间HH(小时):毫米(分钟)一个不同的大小字体的SS(秒)

我一直在看属性文本,但仍然无法得出一些结果


问候。

您可以扩展
NSMutableAttributedString

extension NSMutableAttributedString {
    @discardableResult func resize(_ text: String, _ size: CGFloat) -> NSMutableAttributedString {
        append(NSAttributedString(string: text, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: size)]))
        return self
    }
}
使用方法:

let span = NSMutableAttributedString()
span.resize("HH:", 16.0).resize("MM:", 14.0).resize("SS", 18.0)
label.attributedText = span
就你而言:

let date = Date()
let dateFormatter = DateFormatter()
let span = NSMutableAttributedString()
dateFormatter.dateFormat = "h:"
span.resize(dateFormatter.string(from: date), 16.0)
dateFormatter.dateFormat = "mm:"
span.resize(dateFormatter.string(from: date), 14.0)
dateFormatter.dateFormat = "ss"
span.resize(dateFormatter.string(from: date), 18.0)
timeLabel1.attributedText = span

您也可以尝试使用3种不同的UILabel,每种都根据您的需要进行配置。我只是认为标签需要经常更新,让一个标签代替三个标签会更有效吗?不要认为在一个屏幕上将一个标签分成三个不同的标签会破坏你的表现我想我可以用两个标签代替三个,一个用于HH:MM,另一个用于SS,除非有人知道如何使用属性字符串获得相同的结果。所以我猜我可以使用下面的代码以某种方式实现这一点?Timer=Timer.scheduledTimer(时间间隔:0.2,目标:self,选择器:#选择器(ViewController.setTime),userInfo:nil,repeats:false)let date=NSDate()let dateFormatter=dateFormatter()dateFormatter.dateFormat=“h:mm:ss”let dateString=dateFormatter.string(from:dateas-date)timeLabel1.text=dateStringGreat,这非常好用。现在我只需要在多个设备上测试,我已经设置了一些限制条件,但不确定是否值得通过编程或使用界面生成器进行测试。是否可以通过编程调整字体大小,具体取决于您查看字体的设备?我也有一些限制,但字体大小会覆盖这一点。@Nightowl,我的方法使用硬编码的字体大小值,我认为只有一种方法可以根据查看它的设备来调整大小:设备的if语句如下所示:switch UIScreen.main.nativeBounds.height{case 960:print(“iPhone 4”手机壳1136:print(“iPhone 5/5s/5c/SE”)fontSize1=170 fontSize2=70手机壳1334:print(“iPhone 6/6s/7/8”)手机壳1920、2208:fontSize1=200 fontSize2=70 print(“iPhone 6Plus/6sPlus/7Plus/8Plus”)案例2436:print(“iPhone”)fontSize1=250 fontSize2=100默认值:print(“未知”)}