Skip to content

Instantly share code, notes, and snippets.

@ryanlintott
Last active July 9, 2024 01:29
Show Gist options
  • Save ryanlintott/cae66c6c6ebc17a60b10fb77aa5974c6 to your computer and use it in GitHub Desktop.
Save ryanlintott/cae66c6c6ebc17a60b10fb77aa5974c6 to your computer and use it in GitHub Desktop.
SwiftUI may be clipping your Text views but TextRenderer in iOS 18 might let you fix it in a far less hacky way. Hacky methods that support older OS versions can be found here: https://github.com/ryanlintott/Unicodices
//
// NoClipTextRenderer.swift
//
//
// Created by Ryan Lintott on 2024-07-08.
//
import SwiftUI
@available(iOS 18, *)
struct NoClipTextRenderer: TextRenderer {
let padding: EdgeInsets
func draw(layout: Text.Layout, in context: inout GraphicsContext) {
for line in layout {
context.draw(line)
}
}
func sizeThatFits(proposal: ProposedViewSize, text: TextProxy) -> CGSize {
let textSize = text.sizeThatFits(proposal)
return .init(width: textSize.width + padding.leading + padding.trailing, height: textSize.height + padding.top + padding.bottom)
}
var displayPadding: EdgeInsets {
-padding
}
}
@available(iOS 18, *)
extension View {
func noClip(_ padding: EdgeInsets) -> some View {
self.textRenderer(NoClipTextRenderer(padding: padding))
.padding(-padding)
}
}
#Preview {
VStack {
HStack {
Spacer()
Text("SwiftUI\nText")
Spacer()
Text("NoClip\nTextRenderer")
Spacer()
}
.multilineTextAlignment(.center)
HStack {
Spacer()
Text("f")
.font(.custom("zapfino", size: 30))
.border(Color.red)
Spacer()
if #available(iOS 18, *) {
Text("f")
.font(.custom("zapfino", size: 30))
.noClip(.all(50))
.border(Color.red)
Spacer()
}
}
HStack {
Spacer()
Text("f")
.font(.system(size: 70, weight: .black, design: .serif))
.italic()
.border(Color.red)
Spacer()
if #available(iOS 18, *) {
Text("f")
.font(.system(size: 70, weight: .black, design: .serif))
.italic()
.noClip(.all(20))
.border(Color.red)
Spacer()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment