Widget unable to display Core Data properties - core-data

I am unable to feed and read core data objects/properties into my Widget view. I am only able to feed and present it Doubles/Strings beforehand and it will work.
Prior to this, I have made sure all Core Data related files are shared between both the Widget Extension and the main app. The App Group has been set up and the data can be loaded (I am able to load all transactions in the Provider, calculate the total, and feed that double into the Widget view).
However, when it comes to actually feeding an array of transactions into the Widget View, the data cannot be loaded and all I see are empty rectangles. However, I'm pretty certain the data is accessible as the colours are accurate, and if I display the count of the array, it is accurate too. Below is my attached code.
struct RecentExpenditureWidget: Widget {
let kind: String = "ExpenditureWidget"
var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: RecentWidgetConfigurationIntent.self, provider: Provider()) { entry in
ExpenditureWidgetEntryView(entry: entry)
}
.configurationDisplayName("Recent Transactions")
.description("View your latest expenses.")
.supportedFamilies([.systemSmall])
}
}
struct Provider: IntentTimelineProvider {
typealias Intent = RecentWidgetConfigurationIntent
public typealias Entry = RecentWidgetEntry
func placeholder(in context: Context) -> RecentWidgetEntry {
RecentWidgetEntry(date: Date(), amount: loadAmount(type: .week), transactions: loadTransactions(type: .week, count: 3))
}
func getSnapshot(for configuration: RecentWidgetConfigurationIntent, in context: Context, completion: #escaping (RecentWidgetEntry) -> ()) {
let entry = RecentWidgetEntry(date: Date(), amount: loadAmount(type: configuration.duration), transactions: loadTransactions(type: configuration.duration, count: 3))
completion(entry)
}
func getTimeline(for configuration: RecentWidgetConfigurationIntent, in context: Context, completion: #escaping (Timeline<Entry>) -> ()) {
let entry = RecentWidgetEntry(date: Date(), amount: loadAmount(type: configuration.duration), transactions: loadTransactions(type: configuration.duration, count: 3))
let timeline = Timeline(entries: [entry], policy: .atEnd)
completion(timeline)
}
func loadAmount(type: TimePeriod) -> Double {
let dataController = DataController()
let itemRequest = dataController.fetchRequestForRecentTransactions(type: type)
let transactions = dataController.results(for: itemRequest)
var holdingTotal = 0.0
transactions.forEach { transaction in
holdingTotal += transaction.wrappedAmount
}
return holdingTotal
}
func loadTransactions(type: TimePeriod, count: Int) -> [Transaction] {
let dataController = DataController()
let itemRequest = dataController.fetchRequestForRecentTransactionsWithCount(type: type, count: count)
return dataController.results(for: itemRequest)
}
}
struct RecentWidgetEntry: TimelineEntry {
let date: Date
let amount: Double
let transactions: [Transaction]
}
struct ExpenditureWidgetEntryView : View {
let entry: Provider.Entry
var body: some View {
VStack(spacing: 5) {
ForEach(entry.transactions) { transaction in
HStack(spacing: 2) {
Capsule()
.fill(Color(transaction.category?.wrappedColour ?? ""))
.frame(width: 4)
Text(transaction.wrappedNote)
.lineLimit(1)
.font(.system(size: 12, weight: .regular, design: .rounded))
.foregroundColor(Color.PrimaryText)
Text(transaction.amount, format: .currency(code: Locale.current.currencyCode ?? "USD"))
.font(.system(size: 12, weight: .regular, design: .rounded))
.foregroundColor(Color.SubtitleText)
}
.frame(height: 15)
}
}
.padding(15)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.PrimaryBackground)
}
}
This is the result I get on my actual devices:
The only (by extremely dumb) workaround I have found is to extract each property of a transaction in the loadTransaction() function, and then feed it into the Widget.
func loadTransactions(type: TimePeriod, count: Int) -> String {
let dataController = DataController()
let itemRequest = dataController.fetchRequestForRecentTransactionsWithCount(type: type, count: count)
return dataController.results(for: itemRequest).first!.wrappedNote
}

Related

Publish background context Core Data changes in a SwiftUI view without blocking the UI

After running a background-context core data task, Xcode displays the following purple runtime warning when the updates are published in a SwiftUI view:
"[SwiftUI] Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates."
Besides the ContentView.swift code below, I also added container.viewContext.automaticallyMergesChangesFromParent = true to init in the default Persistence.swift code.
How can I publish the background changes on the main thread to fix the warning? (iOS 14, Swift 5)
Edit: I've changed the code below, in response to the first answer, to clarify that I'm looking for a solution that doesn't block the UI when a lot of changes are saved.
struct PersistenceHelper {
private let context: NSManagedObjectContext
init(context: NSManagedObjectContext = PersistenceController.shared.container.viewContext) {
self.context = context
}
public func fetchItem() -> [Item] {
do {
let request: NSFetchRequest<Item> = Item.fetchRequest()
var items = try self.context.fetch(request)
if items.isEmpty { // Create items if none exist
for _ in 0 ..< 250_000 {
let item = Item(context: context)
item.timestamp = Date()
item.data = "a"
}
try! context.save()
items = try self.context.fetch(request)
}
return items
} catch { assert(false) }
}
public func updateItemTimestamp(completionHandler: #escaping () -> ()) {
PersistenceController.shared.container.performBackgroundTask({ backgroundContext in
let start = Date(), request: NSFetchRequest<Item> = Item.fetchRequest()
do {
let items = try backgroundContext.fetch(request)
for item in items {
item.timestamp = Date()
item.data = item.data == "a" ? "b" : "a"
}
try backgroundContext.save() // Purple warning appears here
let interval = Double(Date().timeIntervalSince(start) * 1000) // Artificial two-second delay so cover view has time to appear
if interval < 2000 { sleep(UInt32((2000 - interval) / 1000)) }
completionHandler()
} catch { assert(false) }
})
}
}
// A cover view with an animation that shouldn't be blocked when saving the background context changes
struct CoverView: View {
#State private var toggle = true
var body: some View {
Circle()
.offset(x: toggle ? -15 : 15, y: 0)
.frame(width: 10, height: 10)
.animation(Animation.easeInOut(duration: 0.25).repeatForever(autoreverses: true))
.onAppear { toggle.toggle() }
}
}
struct ContentView: View {
#State private var items: [Item] = []
#State private var showingCoverView = false
#State private var refresh = UUID()
let persistence = PersistenceHelper()
let formatter = DateFormatter()
var didSave = NotificationCenter.default
.publisher(for: .NSManagedObjectContextDidSave)
// .receive(on: DispatchQuene.main) // Doesn't help
var body: some View {
ScrollView {
LazyVStack {
Button("Update Timestamp") {
showingCoverView = true
persistence.updateItemTimestamp(completionHandler: { showingCoverView = false })
}
ForEach(items, id: \.self) { item in
Text(formatter.string(from: item.timestamp!) + " " + (item.data ?? ""))
}
}
}
.id(refresh)
.onAppear {
formatter.dateFormat = "HH:mm:ss"
items = persistence.fetchItem()
}
.onReceive(didSave) { _ in
items = persistence.fetchItem()
}
.fullScreenCover(isPresented: $showingCoverView) {
CoverView().onDisappear { refresh = UUID() }
}
}
}
Since you are performing a background task, you are on a background thread - rather than the main thread.
To switch to the main thread, change the line producing the runtime warning to the following:
DispatchQueue.main.async {
try backgroundContext.save()
}
You should use Combine and observe changes to your background context and update State values for your UI to react.
#State private var coreDataAttribute = ""
var body: some View {
Text(coreDataAttribute)
.onReceive(
CoreDataManager.shared.moc.publisher(for: \.hasChanges)
.subscribe(on: DispatchQueue.global())
.receive(on: DispatchQueue.global())
.map{_ in CoreDataManager.shared.fetchCoreDataValue()}
.filter{$0 != coreDataAttribute}
.receive(on: DispatchQueue.main))
{ value in
coreDataAttribute = value
}
}

Is this the proper way to use PHPicker in SwiftUI? Because I'm getting a lot of leaks

I am trying to figure out if my code is causing the problem or if I should submit a bug report to Apple.
In a new project, I have this code:
ContentView()
import SwiftUI
struct ContentView: View {
#State private var showingImagePicker = false
#State private var inputImage: UIImage?
#State private var image: Image?
var body: some View {
ZStack {
Rectangle()
.fill(Color.secondary)
if image != nil {
image?
.resizable()
.scaledToFit()
} else {
Text("Tap to select a picture")
.foregroundColor(.white)
.font(.headline)
}
}
.onTapGesture {
self.showingImagePicker = true
}
.sheet(isPresented: $showingImagePicker, onDismiss: loadImage){
SystemImagePicker(image: self.$inputImage)
}
}
func loadImage() {
guard let inputImage = inputImage else { return }
image = Image(uiImage: inputImage)
}
}
SystemImagePicker.swift
import SwiftUI
struct SystemImagePicker: UIViewControllerRepresentable {
#Environment(\.presentationMode) private var presentationMode
#Binding var image: UIImage?
func makeUIViewController(context: Context) -> PHPickerViewController {
var configuration = PHPickerConfiguration()
configuration.selectionLimit = 1
configuration.filter = .images
let picker = PHPickerViewController(configuration: configuration)
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {
}
func makeCoordinator() -> Coordinator {
return Coordinator(parent: self)
}
class Coordinator: NSObject, PHPickerViewControllerDelegate {
let parent: SystemImagePicker
init(parent: SystemImagePicker) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
for img in results {
guard img.itemProvider.canLoadObject(ofClass: UIImage.self) else { return }
img.itemProvider.loadObject(ofClass: UIImage.self) { image, error in
if let error = error {
print(error)
return
}
guard let image = image as? UIImage else { return }
self.parent.image = image
self.parent.presentationMode.wrappedValue.dismiss()
}
}
}
}
}
But when selecting just one image (as per my code, not selecting and then "changing my mind" and selecting another, different image), I get these leaks when running the memory graph in Xcode.
Is it my code, or is this on Apple?
For what it is worth, the Cancel button on the imagepicker doesn't work either. So, the user cannot just close the picker sheet, an image MUST be selected to dismiss the sheet.
Further note on old UIImagePickerController
Previously, I've used this code for the old UIImagePickerController
import SwiftUI
struct ImagePicker: UIViewControllerRepresentable {
#Environment(\.presentationMode) var presentationMode
#Binding var image: UIImage?
class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
let parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let uiImage = info[.originalImage] as? UIImage {
parent.image = uiImage
}
parent.presentationMode.wrappedValue.dismiss()
}
deinit {
print("deinit")
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
}
}
This also result in leaks from choosing an image, but far fewer of them:
I know it's been over a year since you asked this question but hopefully this helps you or someone else looking for the answer.
I used this code in a helper file:
import SwiftUI
import PhotosUI
struct ImagePicker: UIViewControllerRepresentable {
let configuration: PHPickerConfiguration
#Binding var selectedImage: UIImage?
#Binding var showImagePicker: Bool
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> PHPickerViewController {
let picker = PHPickerViewController(configuration: configuration)
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
}
extension ImagePicker {
class Coordinator: NSObject, PHPickerViewControllerDelegate {
private let parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true) {
self.parent.showImagePicker = false
}
guard let provider = results.first?.itemProvider else { return }
if provider.canLoadObject(ofClass: UIImage.self) {
provider.loadObject(ofClass: UIImage.self) { image, _ in
self.parent.selectedImage = image as? UIImage
}
}
parent.showImagePicker = false
}
}
}
This goes in your view (I set up configuration here so I could pass in custom versions depending on what I'm using the picker for, 2 are provided):
#State private var showImagePicker = false
#State private var selectedImage: UIImage?
#State private var profileImage: Image?
var profileConfig: PHPickerConfiguration {
var config = PHPickerConfiguration()
config.filter = .images
config.selectionLimit = 1
config.preferredAssetRepresentationMode = .current
return config
}
var mediaConfig: PHPickerConfiguration {
var config = PHPickerConfiguration()
config.filter = .any(of: [.images, .videos])
config.selectionLimit = 1
config.preferredAssetRepresentationMode = .current
return config
}
This goes in your body. You can customize it how you want but this is what I have so I didn't want to try and piece it out:
HStack {
Button {
showImagePicker.toggle()
} label: {
Text("Select Photo")
.foregroundColor(Color("AccentColor"))
}
.sheet(isPresented: $showImagePicker) {
loadImage()
} content: {
ImagePicker(configuration: profileConfig, selectedImage: $selectedImage, showImagePicker: $showImagePicker)
}
}
if profileImage != nil {
profileImage?
.resizable()
.scaledToFill()
.frame(width: 100, height: 100)
.clipShape(Circle())
.shadow(radius: 5)
.overlay(Circle().stroke(Color.black, lineWidth: 2))
}
else {
Image(systemName: "person.crop.circle")
.resizable()
.foregroundColor(Color("AccentColor"))
.frame(width: 100, height: 100)
}
I will also give you the func for loading the image (I will be resamp:
func loadImage() {
guard let selectedImage = selectedImage else { return }
profileImage = Image(uiImage: selectedImage)
}
I also used this on my Form to update the image if it is changed but you can use it on whatever you're using for your body (List, Form, etc. Whatever takes .onChange):
.onChange(of: selectedImage) { _ in
loadImage()
}
I noticed in a lot of tutorials there is little to no mention of this line which is what makes the cancel button function (I don't know if the closure is necessary but I added it and it worked so I left it in the example):
picker.dismiss(animated: true)
I hope I added everything to help you. It doesn't appear to leak anything and gives you use of the cancel button.
Good luck!

How to use fetch data in Intent Handler for editing Widget iOS 14?

I'm currently developing an application using SwiftUI.
I'm trying to make a widget user can edit some data using IntentConfiguration
I want to use some fetch data from CoreData in IntentHandler class for editing the widget like the image below.
I tried to make some codes but They don't work...
How could I solve my codes?
Here are the codes:
IntentHandler.swift
import WidgetKit
import SwiftUI
import CoreData
import Intents
class IntentHandler: INExtension, ConfigurationIntentHandling {
var moc = PersistenceController.shared.managedObjectContext
var timerEntity_0:TimerEntity?
var timerEntity_1:TimerEntity?
var timerEntity_2:TimerEntity?
init(context : NSManagedObjectContext) {
self.moc = context
let request = NSFetchRequest<TimerEntity>(entityName: "TimerEntity")
do{
let result = try moc.fetch(request)
timerEntity_0 = result[0]
timerEntity_1 = result[1]
timerEntity_2 = result[2]
}
catch let error as NSError{
print("Could not fetch.\(error.userInfo)")
}
}
func provideNameOptionsCollection(for intent: ConfigurationIntent, searchTerm: String?, with completion: #escaping (INObjectCollection<NSString>?, Error?) -> Void) {
let nameIdentifiers:[NSString] = [
NSString(string: timerEntity_0?.task ?? "default"),
NSString(string: timerEntity_1?.task ?? "default"),
NSString(string: timerEntity_2?.task ?? "default")
// "meeting",
// "cooking",
// "shoping"
]
let allNameIdentifiers = INObjectCollection(items: nameIdentifiers)
completion(allNameIdentifiers,nil)
}
override func handler(for intent: INIntent) -> Any {
return self
}
}
Widget.swift
import WidgetKit
import SwiftUI
import Intents
struct Provider: IntentTimelineProvider {
typealias Intent = ConfigurationIntent
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(), configuration: ConfigurationIntent(), name: "")
}
func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: #escaping (SimpleEntry) -> ()) {
let entry = SimpleEntry(date: Date(), configuration: configuration, name: "")
completion(entry)
}
func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: #escaping (Timeline<Entry>) -> ()) {
var entries: [SimpleEntry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = SimpleEntry(date: entryDate, configuration: configuration, name: configuration.Name ?? "")
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}
struct SimpleEntry: TimelineEntry {
let date: Date
let configuration: ConfigurationIntent
var name:String
}
struct TimerIntentWidgetEntryView : View {
var entry: Provider.Entry
var body: some View {
Text(entry.name)
.font(.title)
Text(entry.date, style: .time)
}
}
#main
struct TimerIntentWidget: Widget {
let kind: String = "TimerIntentWidget"
var body: some WidgetConfiguration {
IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
TimerIntentWidgetEntryView(entry: entry)
}
.configurationDisplayName("My Widget")
.description("This is an example widget.")
}
}
tWidget.intentdefinition
Xcode: Version 12.0.1
iOS: 14.0
Life Cycle: SwiftUI App
I could display a list in the widget using fetch data from CoreData like the code below:
IntentHandler.swift
import WidgetKit
import SwiftUI
import CoreData
import Intents
class IntentHandler: INExtension, ConfigurationIntentHandling {
var moc = PersistenceController.shared.managedObjectContext
var timerEntity_0:TimerEntity?
var timerEntity_1:TimerEntity?
var timerEntity_2:TimerEntity?
func provideNameOptionsCollection(for intent: ConfigurationIntent, searchTerm: String?, with completion: #escaping (INObjectCollection<NSString>?, Error?) -> Void) {
let request = NSFetchRequest<TimerEntity>(entityName: "TimerEntity")
do{
let result = try moc.fetch(request)
timerEntity_0 = result[0]
timerEntity_1 = result[1]
timerEntity_2 = result[2]
}
catch let error as NSError{
print("Could not fetch.\(error.userInfo)")
}
let nameIdentifiers:[NSString] = [
NSString(string: timerEntity_0?.task ?? "default"),
NSString(string: timerEntity_1?.task ?? "default"),
NSString(string: timerEntity_2?.task ?? "default")
// "meeting",
// "cooking",
// "shoping"
]
let allNameIdentifiers = INObjectCollection(items: nameIdentifiers)
completion(allNameIdentifiers,nil)
}
override func handler(for intent: INIntent) -> Any {
return self
}
}

Swift UI, removing item from array, while looping in it throws Fatal Error: Index out of range [duplicate]

I am trying to remove rows inside a ForEach. Removing the last row always throws an index out of range exception. Removing any other row does not.
ForEach(Array(player.scores.enumerated()), id: \.element) { index, score in
HStack {
if self.isEditSelected {
Button(action: {
self.player.scores.remove(at: index)
}, label: {
Image("delete")
})
}
TextField("\(score)", value: self.$player.scores[index], formatter: NumberFormatter())
}
}
I have tried using ForEach(player.indices...) & ForEach(player.scores...), but see the same problem.
Looks to me like the crash happens here self.$player.scores[index], as hardcoding the index to any value other that the last row is working.
Does anyone know how to fix this? Or if there is a better approach.
Here is fix
ForEach(Array(player.scores.enumerated()), id: \.element) { index, score in
HStack {
if self.isEditSelected {
Button(action: {
self.player.scores.remove(at: index)
}, label: {
Image("delete")
})
}
TextField("\(score)", value: Binding( // << use proxy binding !!
get: { self.player.scores[index] },
set: { self.player.scores[index] = $0 }),
formatter: NumberFormatter())
}
}
Based on #Asperi answer
public extension Binding where Value: Equatable {
static func proxy(_ source: Binding<Value>) -> Binding<Value> {
self.init(
get: { source.wrappedValue },
set: { source.wrappedValue = $0 }
)
}
}
You can use this as follows:
TextField("Name", text: .proxy($variable))
Xcode 13.0 beta introduced a new way to establish two-way-bindings between the elements of a collection and the views built by ForEach / List.
This method fixes the crash related to deleting the last row.
struct Score: Identifiable {
let id = UUID()
var value: Int
}
struct Player {
var scores: [Score] = (1...10).map {_ in .init(value: Int.random(in: 0...25))}
}
struct BindingTest: View {
#State private var player = Player()
var body: some View {
List {
ForEach($player.scores) { $score in
HStack {
TextField("\(score.value)", value: $score.value,
formatter: NumberFormatter())
}
}
.onDelete { player.scores.remove(atOffsets: $0)}
}
}
}

Set range of colored text for UISegmentedControl

According to the following documentation (https://developer.apple.com/documentation/uikit/uisegmentedcontrol/1618570-settitletextattributes)
I should be able to add attributes to change how it looks for a particular mode.
modalitySegmentedControl.setTitle("LDR ("+(stateController?.tdfvariables.selectedRadionuclide.name ?? "-") + ")", forSegmentAt: Constants.LDRButton)
let colorAttribute = [ NSAttributedString.Key.foregroundColor: UIColor.systemTeal ]
modalitySegmentedControl.setTitleTextAttributes(colorAttribute, for: .selected)
In short the text on the control is basically "LDR (I-125)". Currently this code highlights the entire selection teal. I'm looking for a way to only highlight the (I-125) only with a teal color. I can do this with regular UILabels by defining a range that the attributes act upon, but I can't seem to find a way to set a specific color range with the UISegmentedControl?
Is this possible to do?
It currently looks like this:
I want the LDR to be white color and only teal on the (I-125) part.
In short I think it's not possible. Check my hacky playground:
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
extension UIView {
class func getAllSubviews<T: UIView>(from parentView: UIView) -> [T] {
return parentView.subviews.flatMap { subView -> [T] in
var result = getAllSubviews(from: subView) as [T]
if let view = subView as? T { result.append(view) }
return result
}
}
class func getAllSubviews(from parentView: UIView, types: [UIView.Type]) -> [UIView] {
return parentView.subviews.flatMap { subView -> [UIView] in
var result = getAllSubviews(from: subView) as [UIView]
for type in types {
if subView.classForCoder == type {
result.append(subView)
return result
}
}
return result
}
}
func getAllSubviews<T: UIView>() -> [T] { return UIView.getAllSubviews(from: self) as [T] }
func get<T: UIView>(all type: T.Type) -> [T] { return UIView.getAllSubviews(from: self) as [T] }
func get(all types: [UIView.Type]) -> [UIView] { return UIView.getAllSubviews(from: self, types: types) }
}
class MyViewController : UIViewController {
var myString: String = "LDR (I-125)"
var myString42: String = "424242424242"
var attributedString = NSMutableAttributedString()
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let items = ["EBRT", "LDR (I-125)", "PERM"]
let modalitySegmentedControl = UISegmentedControl(items: items)
modalitySegmentedControl.frame = CGRect(x: 20, y: 200, width: 300, height: 20)
modalitySegmentedControl.backgroundColor = .white
attributedString = NSMutableAttributedString(string: myString, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)])
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: NSRange(location:4, length:7))
let subviews = modalitySegmentedControl.getAllSubviews()
for view in subviews {
if view is UILabel {
if let label = view as? UILabel, label.text == myString {
print(label.attributedText)
label.attributedText = attributedString
//label.text = "42" // this works
print(label.attributedText) // looks changed
}
}
}
let subviews2 = modalitySegmentedControl.getAllSubviews()
for view in subviews2 {
if view is UILabel {
if let label = view as? UILabel, label.text == myString {
print(label.attributedText) // but it didn't change
}
}
}
let lab = UILabel()
lab.frame = CGRect(x: 40, y: 250, width: 300, height: 20)
lab.attributedText = attributedString
view.addSubview(lab)
view.addSubview(modalitySegmentedControl)
self.view = view
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
You can find specific UILabel subview of UISegmentedControl and even can change the text, but attribute changes doesn't work.
Related question: Segmented Control set attributed title in each segment

Resources