简体   繁体   中英

How do I set a weight to SF Symbols for iOS 13?

I have this

Image(systemName: "arrow.right")

But how do I make it bold, semibold etc?

I am using the new SwiftUI.

When using the font modifier, set a weight to the font you're passing.

For example, if you want to use one of the default text styles (which I recommend, since they adapt to the user's Dynamic Type setting), you can do it like this:

Image(systemName: "arrow.right")
  .font(Font.title.weight(.ultraLight))

If you want to specify a font size, you can do it like this:

Image(systemName: "arrow.right")
  .font(Font.system(size: 60, weight: .ultraLight))

For UIKit, symbols can be configured as follows:

UIImage(systemName: "arrow.right",
        withConfiguration: UIImage.SymbolConfiguration(pointSize: 16, weight: .bold))

SwiftUI 1.0

I just wanted to also mention how to change the weight along with a custom font size.

HStack(spacing: 40) {
    Image(systemName: "moon.zzz")
        .font(Font.system(size: 60, weight: .ultraLight))
    Image(systemName: "moon.zzz")
        .font(Font.system(size: 60, weight: .light))
    Image(systemName: "moon.zzz")
        .font(Font.system(size: 60, weight: .regular))
    Image(systemName: "moon.zzz")
        .font(Font.system(size: 60, weight: .bold))
}

字体大小和粗细示例

UIKit -- Swift 5 -- Xcode 11

If you only want to set the weight (so you don't mess up auto icon sizing), do this:

let configuration = UIImage.SymbolConfiguration(weight: .semibold)
UIImage(systemName: "trash", withConfiguration: configuration)

UIKit SWIFT 5.x

To set their attributes: create a configuration then pass it in as a parameter:

let imageConfig = UIImage.SymbolConfiguration(pointSize: 22, weight: .black, scale: .large)
let image = UIImage(systemName: "delete.right", withConfiguration: imageConfig)

You can also wrap the Image with Text . With that you can use and assign the fontWeight() to Text :

Text(Image(systemName: "xmark"))
    .fontWeight(.semibold)

Xcode 13.4, Swift 5.X

import UIKit
import SwiftUI


public extension Image {
    
    @available(iOS 13.0, *)
    static func buildSystemImage(named systemName: String, weightConfiguration: UIImage.SymbolWeight) -> Image? {
        guard let imageConfig = UIImage(systemName: systemName, withConfiguration: UIImage.SymbolConfiguration(weight: weightConfiguration)) else { return nil }
        return Image(uiImage: imageConfig)
    }
}

Usage:

if let systemImage = Image.buildSystemImage(named: "arrow.left", weightConfiguration: .semibold) {
    // Your code.                
}

For iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, you can use fontWeight() directly on the Image() .

Image(systemName: "chevron.right")
    .fontWeight(.semibold)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM