Combine two x-y plots using SwiftUI and the Charts Library - swiftui

I am working with SwiftUI and the Charts Library (ie import Charts)
All OK with producing a singe line.
However I want to plot 2 separate lines on the chart
But cannot work out how to do this
I call the struct with the following line:
myLineChartSwiftUI(myXminny: self.$myXminny, myXmaxy: self.$myXmaxy)
I have added the 2nd line setup (ie dataPoints2, set2, color2 etc )
How the hell do I combine the 2 lines to return then for the plot?
Help would be very much appreciated
My first swiftUI and 1st Charts program:
struct myLineChartSwiftUI : UIViewRepresentable
{
#Binding var myXminny : Double
#Binding var myXmaxy : Double
let lineChart = LineChartView()
func makeUIView(context: UIViewRepresentableContext<myLineChartSwiftUI>) -> LineChartView {
setUpChart()
return lineChart
}
func updateUIView(_ uiView: LineChartView, context: UIViewRepresentableContext<myLineChartSwiftUI>) {
}
func setUpChart() {
let dataSets = [getLineChartDataSet()]
let data = LineChartData(dataSets: dataSets)
lineChart.data = data
}
func getChartDataPoints(sessions: [Double], accuracy: [Double]) -> [ChartDataEntry] {
var dataPoints: [ChartDataEntry] = []
for count in (0..<sessions.count) {
dataPoints.append(ChartDataEntry.init(x: Double(sessions[count]), y: accuracy[count]))
}
return dataPoints
}
func getLineChartDataSet() -> LineChartDataSet {
let dataPoints = getChartDataPoints(sessions: [myXminny,myXmaxy], accuracy: [myXminny,myXmaxy])
let set = LineChartDataSet(entries: dataPoints, label: "DataSet")
set.lineWidth = 2
set.drawValuesEnabled = false
set.drawCirclesEnabled = false
//set.circleRadius = 4
let color = ChartColorTemplates.vordiplom()[4]
set.setColor(color)
let dataPoints2 = getChartDataPoints(sessions: [myXminny/2,myXmaxy/2], accuracy: [myXminny/2,myXmaxy/2])
let set2 = LineChartDataSet(entries: dataPoints2, label: "DataSet2")
set2.lineWidth = 2
set2.drawValuesEnabled = false
set2.drawCirclesEnabled = false
let color2 = ChartColorTemplates.vordiplom()[4]
set2.setColor(color2)
let data = LineChartData(dataSets: [set, set2])
return set
}
}

For those of you interested in a solution, the code is as follows:
import SwiftUI
import Charts
struct GraphSwiftUI: View {
var body: some View {
GeometryReader { p in
VStack {
LineChartSwiftUI()
//use frame to change the graph size within your SwiftUI view
.frame(width: p.size.width, height: p.size.width, alignment: .center)
}
}
}
}
struct LineChartSwiftUI: UIViewRepresentable {
let lineChart = LineChartView()
func makeUIView(context: UIViewRepresentableContext<LineChartSwiftUI>) -> LineChartView {
setUpChart()
return lineChart
}
func updateUIView(_ uiView: LineChartView, context: UIViewRepresentableContext<LineChartSwiftUI>) {
}
func setUpChart() {
let dataSets = [getLineChartDataSet()]
let data = LineChartData(dataSets: dataSets)
}
func getChartDataPoints(sessions: [Int], accuracy: [Double]) -> [ChartDataEntry] {
var dataPoints: [ChartDataEntry] = []
for count in (0..<sessions.count) {
dataPoints.append(ChartDataEntry.init(x: Double(sessions[count]), y: accuracy[count]))
}
return dataPoints
}
func getLineChartDataSet() -> LineChartDataSet {
let dataPoints = getChartDataPoints(sessions: [0,1,5], accuracy: [0, 2, 8])
let set = LineChartDataSet(entries: dataPoints, label: "DataSet")
set.lineWidth = 3
let color = ChartColorTemplates.vordiplom()[4]
set.setColor(color)
let dataPoints2 = getChartDataPoints(sessions: [0,1,5], accuracy: [50,10,15])
let set2 = LineChartDataSet(entries: dataPoints2, label: "DataSet2")
set2.lineWidth = 2
set2.drawValuesEnabled = true
set2.drawCirclesEnabled = true
let color2 = ChartColorTemplates.vordiplom()[3]
set2.setColor(color2)
let data = LineChartData(dataSets: [set, set2])
lineChart.data = data
return set
}
}
struct GraphSwiftUI_Previews: PreviewProvider {
static var previews: some View {
GraphSwiftUI()
}
}

Related

List is jumpy when items are changed

I implemented a location search view with locations suggested per user query. The issue is every time when the input text is changed, there will be a momentary rendering error.
Here is the reproducible code snippet. I tried to remove the debounce implementation, but the issue still existed.
import SwiftUI
import MapKit
struct ContentView: View {
#StateObject private var vm = LocationChooserViewModel()
#State var query: String = ""
let center = CLLocationCoordinate2D(latitude: 116.3975, longitude: 39.9087)
var body: some View {
VStack {
TextField("Type to search", text: $query)
.onChange(of: query) { newQuery in
vm.scheduledSearch(by: newQuery, around: center)
}
List {
if vm.mapItems.count > 0 {
Section("Locations") {
ForEach(vm.mapItems, id: \.self) { mapItem in
Text(mapItem.name ?? "")
}
}
}
}
.listStyle(.grouped)
Spacer()
}
.padding()
}
}
class LocationChooserViewModel: ObservableObject {
#Published var mapItems: [MKMapItem] = []
private var timer: Timer? = nil
func scheduledSearch(by query: String, around center: CLLocationCoordinate2D) -> Void {
timer?.invalidate()
guard query.trimmingCharacters(in: .whitespaces) != "" else {
mapItems = []
return
}
timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: false, block: { _ in
self.performSearch(by: query, around: center)
})
}
private func performSearch(by query: String, around center: CLLocationCoordinate2D) -> Void {
let searchRequest = MKLocalSearch.Request()
searchRequest.naturalLanguageQuery = query
let search = MKLocalSearch(request: searchRequest)
search.start { response, _ in
self.mapItems = response?.mapItems ?? []
}
}
}
------------ Update 5/3 ------------
I happened to learn about the differences between ForEach and List in What is the difference between List and ForEach in SwiftUI?. I tried to replace ForEach(vm.mapItems) by ForEach(0..<vm.mapItems.count). It works, but I'm still not sure whether it's an efficient way to do it.
It might be an effect of overlapped results delivery. Try to do two things: a) cancel previous search request, b) update result on main queue:
class LocationChooserViewModel: ObservableObject {
#Published var mapItems: [MKMapItem] = []
private var timer: Timer? = nil
private var search: MKLocalSearch? = nil // << here !!
func scheduledSearch(by query: String, around center: CLLocationCoordinate2D) -> Void {
timer?.invalidate()
guard query.trimmingCharacters(in: .whitespaces) != "" else {
mapItems = []
return
}
timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: false, block: { _ in
self.performSearch(by: query, around: center)
})
}
private func performSearch(by query: String, around center: CLLocationCoordinate2D) -> Void {
let searchRequest = MKLocalSearch.Request()
searchRequest.naturalLanguageQuery = query
self.search?.cancel() // << here !!
self.search = MKLocalSearch(request: searchRequest)
self.search?.start { response, _ in
DispatchQueue.main.async { // << here !!
self.mapItems = response?.mapItems ?? []
}
}
}
}
Alternate is to switch to Combine with .debounce.

How can I make SceneView's background transparent?

I want to open a 3D model and make its background transparent, so that I can see the UI behind the SceneView. I've tried this code, but sceneView becomes white, not transparent.
struct ModelView: View {
var body: some View {
ZStack {
Text("Behind Text Behind Text Behind Text")
SceneView(
scene: { () -> SCNScene in
let scene = SCNScene()
scene.background.contents = UIColor.clear
return scene
}(),
pointOfView: { () -> SCNNode in
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.position = SCNVector3(x: 0, y: 0, z: 10)
return cameraNode
}(),
options: [
.allowsCameraControl,
.temporalAntialiasingEnabled,
]
)
}
}
}
I use XCode 12.5 and IPhone 8.
EDIT 1:
Thanks to the comments below, I decided to try new approaches but they still don't work.
Approach #1
First, I tried to create a MySceneView using SCNView through UIViewRepresentable:
struct MySceneView: UIViewRepresentable {
typealias UIViewType = SCNView
typealias Context = UIViewRepresentableContext<MySceneView>
func updateUIView(_ uiView: UIViewType, context: Context) {}
func makeUIView(context: Context) -> UIViewType {
let view = SCNView()
view.allowsCameraControl = true
view.isTemporalAntialiasingEnabled = true
view.autoenablesDefaultLighting = true
view.scene = MySceneView.scene
return view
}
static let scene: SCNScene = {
let scene = SCNScene(named: "art.scnassets/man.obj")!
scene.background.contents = UIColor.clear
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.position = SCNVector3(x: 0, y: 0, z: 10)
scene.rootNode.addChildNode(cameraNode)
return scene
}()
}
Approach #2
I tried using SpriteView, here is the code:
ZStack {
Text("Behind Text Behind Text Behind Text")
SpriteView(scene: { () -> SKScene in
let scene = SKScene()
scene.backgroundColor = UIColor.clear
let model = SK3DNode(viewportSize: .init(width: 200, height: 200))
model.scnScene = MySceneView.scene
scene.addChild(model)
return scene
}(), options: [.allowsTransparency])
}
Update:
A much simpler solution is to use UIViewRepresentable, create SCNView and set backgroundColor to clear
Old:
Thanks George_E, your idea with SpriteKit worked perfectly. Here is the code:
SpriteView(scene: { () -> SKScene in
let scene = SKScene()
scene.backgroundColor = UIColor.clear
let model = SK3DNode(viewportSize: .init(width: 200, height: 200))
model.scnScene = {
let scene = SCNScene(named: "art.scnassets/man.obj")!
scene.background.contents = UIColor.clear
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.position = SCNVector3(x: 0, y: 0, z: 10)
scene.rootNode.addChildNode(cameraNode)
return scene
}()
scene.addChild(model)
return scene
}(), options: [.allowsTransparency])
I wasn't able to find a fully working snippet here, but thanks to the answers from Arutyun I managed to compile a working solution without the need for SpriteKit.
import SceneKit
import SwiftUI
struct MySceneView: UIViewRepresentable {
typealias UIViewType = SCNView
typealias Context = UIViewRepresentableContext<MySceneView>
func updateUIView(_ uiView: UIViewType, context: Context) {}
func makeUIView(context: Context) -> UIViewType {
let view = SCNView()
view.backgroundColor = UIColor.clear // this is key!
view.allowsCameraControl = true
view.autoenablesDefaultLighting = true
// load the object here, could load a .scn file too
view.scene = SCNScene(named: "model.obj")!
return view
}
}
And use it just like a regular view:
import SwiftUI
struct MySceneView: View {
var body: some View {
ZStack{
// => background views here
MySceneView()
.frame( // set frame as required
maxWidth: .infinity,
maxHeight: .infinity,
alignment: .center
)
}
}
}
struct MySceneView_Previews: PreviewProvider {
static var previews: some View {
MySceneView()
}
}
With SwiftUI:
It is slightly different in SwiftUI using a SpriteView.
To implement a transparent SpriteView in SwiftUI, you have to use the 'options' parameter:
Configure your SKScene with clear background (view AND scene)
Configure your SpriteView with the correct option
// 1. configure your scene in 'didMove'
override func didMove(to view: SKView) {
self.backgroundColor = .clear
view.backgroundColor = .clear
}
and most importantly:
// 2. configure your SpriteView with 'allowsTranspanency'
SpriteView(scene: YourSKScene(), options: [.allowsTransparency])
I didn't like using SpriteKit to make a SceneKit scenes background contents transparent because you completely loose access to the SCNView. Here is what I believe to be the correct approach.
Create a Scene Kit Scene file named GameScene.scn
Drop your 3D object into the GameScene
Use the code below
/// The SCNView view
struct GameSceneView: UIViewRepresentable {
#ObservedObject var viewModel: GameSceneViewModel
func makeUIView(context: UIViewRepresentableContext<GameSceneView>) -> SCNView {
let view = SCNView()
view.backgroundColor = viewModel.backgroundColor
view.allowsCameraControl = viewModel.allowsCameraControls
view.autoenablesDefaultLighting = viewModel.autoenablesDefaultLighting
view.scene = viewModel.scene
return view
}
func updateUIView(_ uiView: SCNView, context: UIViewRepresentableContext<GameSceneView>) {}
}
/// The view model supplying the SCNScene and its properties
class GameSceneViewModel: ObservableObject {
#Published var scene: SCNScene?
#Published var backgroundColor: UIColor
#Published var allowsCameraControls: Bool
#Published var autoenablesDefaultLighting: Bool
init(
sceneName: String = "GameScene.scn",
cameraName: String = "camera",
backgroundColor: UIColor = .clear,
allowsCameraControls: Bool = true,
autoenablesDefaultLighting: Bool = true
) {
self.scene = SCNScene(named: sceneName)
self.backgroundColor = backgroundColor
self.allowsCameraControls = allowsCameraControls
self.autoenablesDefaultLighting = autoenablesDefaultLighting
scene?.background.contents = backgroundColor
scene?.rootNode.childNode(withName: cameraName, recursively: false)
}
}
/// Usage
struct ContentView: View {
var body: some View {
VStack {
GameSceneView(viewModel: GameSceneViewModel())
}
.background(Color.blue)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

swiftUI Synchronous issue with running a function before I have calculated the data for the ZStack element

I am using SwiftUI but have a conceptual problem.
I have edited down my code for (hopefully to fully explain the issue )
I want to do some calculations after the button is pressed AFTER which I want to plot the graph.
I am using minX as the bogus result of calculations.
Firstly, note that I have a file (called myGlobal.swift) the contents of which are:
import Foundation
class myGlobalVariables: ObservableObject
{
#Published var minX :Double = 99999
}
The value of this in the getLineChartDataSet = 9999
(from the Global file)
Before I press the button
This changed after I press the button to 222.222 in Mohrs2DCalc func
But of course I have already run myLineChartSwiftUI before I pressed the button,
But want to run myLineChartSwiftUI only AFTER I have pressed the button
import SwiftUI
import Charts
struct PricipalStresses2D: View {
#ObservedObject var input = myGlobalVariables()
var body: some View
{
ScrollView(.vertical, showsIndicators: true)
{
VStack(spacing: -10)
{
Button(action: {
self.CheckInputs()
})
{
Text("Calculations Before Plot")
}.padding(50)
myLineChartSwiftUI() //use frame to change the graph size within your SwiftUI view
.frame(alignment: .center)
.aspectRatio(contentMode: .fit)
}
}
}
func CheckInputs()
{
//Assume all inputs are OK
self.Mohrs2DCalc()
}
func Mohrs2DCalc()
{
let minX = 222.222 // Just to set it as if we had calculated it
self.input.minX = minX
print("Mohrs circle minX = \(self.input.minX)")
}
struct myLineChartSwiftUI : UIViewRepresentable
{
let lineChart = LineChartView()
func makeUIView(context: UIViewRepresentableContext<myLineChartSwiftUI>) -> LineChartView {
setUpChart()
return lineChart
}
func updateUIView(_ uiView: LineChartView, context: UIViewRepresentableContext<myLineChartSwiftUI>) {
}
func setUpChart() {
//lineChart.noDataText = "No Data Available"
let dataSets = [getLineChartDataSet()]
let data = LineChartData(dataSets: dataSets)
//data.setValueFont(.systemFont(ofSize: 7, weight: .light))
lineChart.data = data
}
func getChartDataPoints(sessions: [Int], accuracy: [Double]) -> [ChartDataEntry] {
var dataPoints: [ChartDataEntry] = []
for count in (0..<sessions.count) {
dataPoints.append(ChartDataEntry.init(x: Double(sessions[count]), y: accuracy[count]))
}
return dataPoints
}
func getLineChartDataSet() -> LineChartDataSet {
print("In getLineChartDataSet, minX = ", myGlobalVariables.self.init().minX) // This works fine
let dataPoints = getChartDataPoints(sessions: [0,1], accuracy: [0.0,10.0]) // sessions = x, accuracy = y
let set = LineChartDataSet(entries: dataPoints, label: "DataSet")
set.lineWidth = 0
//set.circleRadius = 4
//set.circleHoleRadius = 2
let color = ChartColorTemplates.vordiplom()[4]
set.setColor(color)
//set.setCircleColor(color)
// Got to set the xMin and xMax from the global to obtain it here
return set
}
}
} //View
struct PricipalStresses2D_Previews: PreviewProvider {
static var previews: some View {
PricipalStresses2D()
}
}
Your help will be appreciated,
TIA, Phil.

How to render multiline text in SwiftUI List with correct height?

I would like to have a SwiftUI view that shows many lines of text, with the following requirements:
Works on both macOS and iOS.
Shows a large number of strings (each string is backed by a separate model object).
I can do arbitrary styling to the multiline text.
Each string of text can be of arbitrary length, possibly spanning multiple lines and paragraphs.
The maximum width of each string of text is fixed to the width of the container. Height is variable according to the actual length of text.
There is no scrolling for each individual text, only the list.
Links in the text must be tappable/clickable.
Text is read-only, does not have to be editable.
Feels like the most appropriate solution would be to have a List view, wrapping native UITextView/NSTextView.
Here’s what I have so far. It implements most of the requirements EXCEPT having the correct height for the rows.
//
// ListWithNativeTexts.swift
// SUIToy
//
// Created by Jaanus Kase on 03.05.2020.
// Copyright © 2020 Jaanus Kase. All rights reserved.
//
import SwiftUI
let number = 20
struct ListWithNativeTexts: View {
var body: some View {
List(texts(count: number), id: \.self) { text in
NativeTextView(string: text)
}
}
}
struct ListWithNativeTexts_Previews: PreviewProvider {
static var previews: some View {
ListWithNativeTexts()
}
}
func texts(count: Int) -> [String] {
return (1...count).map {
(1...$0).reduce("Hello https://example.com:", { $0 + " " + String($1) })
}
}
#if os(iOS)
typealias NativeFont = UIFont
typealias NativeColor = UIColor
struct NativeTextView: UIViewRepresentable {
var string: String
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.isEditable = false
textView.isScrollEnabled = false
textView.dataDetectorTypes = .link
textView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textView.textContainer.lineFragmentPadding = 0
let attributed = attributedString(for: string)
textView.attributedText = attributed
return textView
}
func updateUIView(_ textView: UITextView, context: Context) {
}
}
#else
typealias NativeFont = NSFont
typealias NativeColor = NSColor
struct NativeTextView: NSViewRepresentable {
var string: String
func makeNSView(context: Context) -> NSTextView {
let textView = NSTextView()
textView.isEditable = false
textView.isAutomaticLinkDetectionEnabled = true
textView.isAutomaticDataDetectionEnabled = true
textView.textContainer?.lineFragmentPadding = 0
textView.backgroundColor = NSColor.clear
textView.textStorage?.append(attributedString(for: string))
textView.isEditable = true
textView.checkTextInDocument(nil) // make links clickable
textView.isEditable = false
return textView
}
func updateNSView(_ textView: NSTextView, context: Context) {
}
}
#endif
func attributedString(for string: String) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: string)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
let range = NSMakeRange(0, (string as NSString).length)
attributedString.addAttribute(.font, value: NativeFont.systemFont(ofSize: 24, weight: .regular), range: range)
attributedString.addAttribute(.foregroundColor, value: NativeColor.red, range: range)
attributedString.addAttribute(.backgroundColor, value: NativeColor.yellow, range: range)
attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: range)
return attributedString
}
Here’s what it outputs on iOS. macOS output is similar.
How do I get this solution to size the text views with correct heights?
One approach that I have tried, but not shown here, is to give the height “from outside in” - to specify the height on the list row itself with frame. I can calculate the height of an NSAttributedString when I know the width, which I can obtain with geoReader. This almost works, but is buggy, and does not feel right, so I’m not showing it here.
Sizing List rows doesn't work well with SwiftUI.
However, I have worked out how to display a scroll of native UITextViews in a stack, where each item is dynamically sized based on the height of its attributedText.
I have put 2 point spacing between each item and tested with 80 items
using your text generator.
Here are the first three screenshots of scroll, and another screenshot
showing the very end of the scroll.
Here is the full class with extensions for attributedText height and regular string size, as well.
import SwiftUI
let number = 80
struct ListWithNativeTexts: View {
let rows = texts(count:number)
var body: some View {
GeometryReader { geometry in
ScrollView {
VStack(spacing: 2) {
ForEach(0..<self.rows.count, id: \.self) { i in
self.makeView(geometry, text: self.rows[i])
}
}
}
}
}
func makeView(_ geometry: GeometryProxy, text: String) -> some View {
print(geometry.size.width, geometry.size.height)
// for a regular string size (not attributed text)
// let textSize = text.size(width: geometry.size.width, font: UIFont.systemFont(ofSize: 17.0, weight: .regular), padding: UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0))
// print("textSize: \(textSize)")
// return NativeTextView(string: text).frame(width: geometry.size.width, height: textSize.height)
let attributed = attributedString(for: text)
let height = attributed.height(containerWidth: geometry.size.width)
print("height: \(height)")
return NativeTextView(string: text).frame(width: geometry.size.width, height: height)
}
}
struct ListWithNativeTexts_Previews: PreviewProvider {
static var previews: some View {
ListWithNativeTexts()
}
}
func texts(count: Int) -> [String] {
return (1...count).map {
(1...$0).reduce("Hello https://example.com:", { $0 + " " + String($1) })
}
}
#if os(iOS)
typealias NativeFont = UIFont
typealias NativeColor = UIColor
struct NativeTextView: UIViewRepresentable {
var string: String
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.isEditable = false
textView.isScrollEnabled = false
textView.dataDetectorTypes = .link
textView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textView.textContainer.lineFragmentPadding = 0
let attributed = attributedString(for: string)
textView.attributedText = attributed
// for a regular string size (not attributed text)
// textView.font = UIFont.systemFont(ofSize: 17.0, weight: .regular)
// textView.text = string
return textView
}
func updateUIView(_ textView: UITextView, context: Context) {
}
}
#else
typealias NativeFont = NSFont
typealias NativeColor = NSColor
struct NativeTextView: NSViewRepresentable {
var string: String
func makeNSView(context: Context) -> NSTextView {
let textView = NSTextView()
textView.isEditable = false
textView.isAutomaticLinkDetectionEnabled = true
textView.isAutomaticDataDetectionEnabled = true
textView.textContainer?.lineFragmentPadding = 0
textView.backgroundColor = NSColor.clear
textView.textStorage?.append(attributedString(for: string))
textView.isEditable = true
textView.checkTextInDocument(nil) // make links clickable
textView.isEditable = false
return textView
}
func updateNSView(_ textView: NSTextView, context: Context) {
}
}
#endif
func attributedString(for string: String) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: string)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
let range = NSMakeRange(0, (string as NSString).length)
attributedString.addAttribute(.font, value: NativeFont.systemFont(ofSize: 24, weight: .regular), range: range)
attributedString.addAttribute(.foregroundColor, value: NativeColor.red, range: range)
attributedString.addAttribute(.backgroundColor, value: NativeColor.yellow, range: range)
attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: range)
return attributedString
}
extension String {
func size(width:CGFloat = 220.0, font: UIFont = UIFont.systemFont(ofSize: 17.0, weight: .regular), padding: UIEdgeInsets? = nil) -> CGSize {
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = self
label.sizeToFit()
if let pad = padding{
// add padding
return CGSize(width: label.frame.width + pad.left + pad.right, height: label.frame.height + pad.top + pad.bottom)
} else {
return CGSize(width: label.frame.width, height: label.frame.height)
}
}
}
extension NSAttributedString {
func height(containerWidth: CGFloat) -> CGFloat {
let rect = self.boundingRect(with: CGSize.init(width: containerWidth, height: CGFloat.greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
context: nil)
return ceil(rect.size.height)
}
func width(containerHeight: CGFloat) -> CGFloat {
let rect = self.boundingRect(with: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: containerHeight),
options: [.usesLineFragmentOrigin, .usesFontLeading],
context: nil)
return ceil(rect.size.width)
}
}
Jeaanus,
I am not sure I understand your question entirely, but there are a couple of environmental variables and Insets you can add to change on SwiftUI List views spacing... Here is an example of what I am talking about.
Note it is important you add them to the right view, the listRowInsets is on the ForEach, the environment is on the List view.
List {
ForEach((0 ..< self.selections.count), id: \.self) { column in
HStack(spacing:0) {
Spacer()
Text(self.selections[column].name)
.font(Fonts.avenirNextCondensedBold(size: 22))
Spacer()
}
}.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
}.environment(\.defaultMinListRowHeight, 20)
.environment(\.defaultMinListHeaderHeight, 0)
.frame(width: UIScreen.main.bounds.size.width, height: 180.5, alignment: .center)
.offset(x: 0, y: -64)
Mark

SwiftUI how to create List with custom UIViews inside it

I consider how to create SwitUI List that has as its row custom UIViews.
I create List:
List {
RowView()
}
RowView is UIViewRepresentable of UIRowView
struct RowView : UIViewRepresentable {
func makeUIView() -> UIRowView { ... }
}
UIRowView is custom view
UIRowView: UIView { ... }
Currently first rows are displayed but they are usually not layout properly and while scrolling this views disappear instead of being recycled
UPDATE
Example 1
struct NoteView: UIViewRepresentable {
// MARK: - Properties
let note: Note
let date = Date()
func makeUIView(context: Context) -> UINoteView {
let view = UINoteView()
view.note = note
return view
}
func updateUIView(_ uiView: UINoteView, context: Context) {
uiView.note = note
print("View bounds: \(uiView.bounds)")
}
}
var body: some View {
List {
ForEach(Array(notes.enumerated()), id: \.1) { (i, note) in
NoteView(note: note)
.background(Color.green)
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
}
}.background(Color.red)
}
Example 2 - Simplified
struct TestView : UIViewRepresentable {
let text : String
func makeUIView(context: Context) -> UILabel {
UILabel()
}
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.text = text
}
}
var body: some View {
List {
ForEach(0..<30, id: \.self) { i in
TestView(text: "\(i)")
}
}
}
Both seems to work incorrectly, as rows dissapears
I had also issue with views not keeping padding and going outside of the screen if there was more content. Only several first rows (visible initially on screen layouts correctly) other disappears or jump somewhere.
UPDATE 2
Here is Autosizable UINoteView
class UINoteView: UIView {
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
// MARK: - Properties
var note: Note? {
didSet {
textView.attributedText = note?.content?.parsedHtmlAttributedString(textStyle: .html)
noteFooterViewModel.note = note
}
}
// MARK: - Views
lazy var textView: UITextView = {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.backgroundColor = UIColor.yellow
textView.textContainer.lineBreakMode = .byWordWrapping
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.isScrollEnabled = false
textView.isSelectable = true
textView.isUserInteractionEnabled = true
textView.isEditable = false
textView.textContainer.maximumNumberOfLines = 0
return textView
}()
lazy var label: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "TEST ROW \(note?.id ?? "")"
return label
}()
lazy var vStack: UIStackView = {
let stack = UIStackView(arrangedSubviews: [
textView,
noteFooter
])
stack.axis = .vertical
stack.alignment = .fill
stack.distribution = .fill
stack.translatesAutoresizingMaskIntoConstraints = false
return stack
}()
var noteFooterViewModel = NoteFooterViewModel()
var noteFooter: UIView {
let footer = NoteFooter(viewModel: noteFooterViewModel)
let hosting = UIHostingController(rootView: footer)
hosting.view.translatesAutoresizingMaskIntoConstraints = false
return hosting.view
}
private func setupViews() {
self.backgroundColor = UIColor.green
self.addSubview(vStack)
NSLayoutConstraint.activate([
vStack.leadingAnchor.constraint(equalTo: self.leadingAnchor),
vStack.trailingAnchor.constraint(equalTo: self.trailingAnchor),
vStack.topAnchor.constraint(equalTo: self.topAnchor),
vStack.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
}
UPDATED ANSWER
try this:
struct TestView : UIViewRepresentable {
let text : String
var label : UILabel = UILabel()
func makeUIView(context: Context) -> UILabel {
return label
}
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.text = text
}
}
struct ContentView : View {
var body: some View {
List (0..<30, id: \.self) { i in
TestView(text: "\(i)").id(i)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I did like below. You can get the frame size even without UIViewRepresentable by getTextFrame(for note)
var body: some View {
List {
ForEach(Array(notes.enumerated()), id: \.1) { (i, note) in
NoteView(note: note)
// add this
.frame(width: getTextFrame(for: note).width, height: getTextFrame(for: note).height)
.background(Color.green)
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
}
}.background(Color.red)
}
func getTextFrame(for text: String, maxWidth: CGFloat? = nil, maxHeight: CGFloat? = nil) -> CGSize {
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.preferredFont(forTextStyle: .body)
]
let attributedText = NSAttributedString(string: text, attributes: attributes)
let width = maxWidth != nil ? min(maxWidth!, CGFloat.greatestFiniteMagnitude) : CGFloat.greatestFiniteMagnitude
let height = maxHeight != nil ? min(maxHeight!, CGFloat.greatestFiniteMagnitude) : CGFloat.greatestFiniteMagnitude
let constraintBox = CGSize(width: width, height: height)
let rect = attributedText.boundingRect(with: constraintBox, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).integral
print(rect.size)
return rect.size
}
struct NoteView: UIViewRepresentable {
let note: String
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.delegate = context.coordinator
textView.font = UIFont.preferredFont(forTextStyle: .body)
textView.isEditable = false
textView.isSelectable = true
textView.isUserInteractionEnabled = true
textView.isScrollEnabled = false
textView.backgroundColor = .clear
textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.textContainer.lineBreakMode = .byWordWrapping
textView.text = note
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
}
}