This is my struct view for the overflow menu
struct OverflowMenu: View {
var body: some View {
Menu {
NavigationLink(destination: SettingView()) {
Label{
Text("Settings")
}
icon: {
Awesome.Solid.cog.image
.foregroundColor(UIColor(hex: "#ffbd16"))
}
}
} label: {
Image(systemName: "ellipsis.circle")
}
}
}
Nothing happens when the button is clicked. The SettingsView is not shown in a new window. And the OverflowMenuView() is inside the NavigationView. Am i missing something else?
var body: some View {
NavigationView {
.....
HStack {
Spacer()
OverflowMenu()
}
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Anyone got sample code for using AVPlayerLooper in SwiftUI?
Code i see are not for SwiftUI
I only wish to have the option to turn on auto-repeat on and off.
I could use AVQueuePlayer as replacement for AVPlayer but it does not have a way to loop.
So these are what I am looking for
Loop video in SwiftUI
If Using AVPlayerLooper, it has a disableLooping() function (possibly to turn off looping). But how can it be turned back on? There is no enableLooping(). Or does it need a new instance?
since i am new to iOS, the code there are all linked to no swift ui code so I have no clue (sorry) the equivalent of them in SwiftUI
Thoughts?
Hi all. I am not sure what is wrong with my current code. What I am looking to do is change all values of a string with a substring of "around #C"
where # is the temperature. I am converting between farenheit and celsius and i wish to get all substrings then change the correct value depending on the current setting.
So if i have a string where
"This is today. The temperature is around 14C. Tomorrow the temperature will be around 18C"
So the regex would get "around 14C" and "around 18C" and change the values to farenheit. Result would be something like
"This is today. The temperature is around -1F. Tomorrow the temperature will be around -4F"
This is my function.
func formatCorrectDetail(_ detail: String, _ isCelsius: Bool) -> String {
let regex = try! NSRegularExpression(pattern: "around ((\\d+)" + (isCelsius ? "F" : "C") + ")", options: [])
let matches = regex.matches(in: detail, options: [], range: NSRange(location: 0, length: detail.utf16.count))
let formattedString = NSMutableString(string: detail)
for match in matches {
let range = match.range(at: 2)
if let rangeSubstring = Range(range, in: detail),
let temperature = Double(String(detail[rangeSubstring])) {
let val = isCelsius ? NumberTool.far2cel(temperature) : NumberTool.cel2far(temperature)
formattedString.replaceCharacters(in: range, with: val)
}
}
if formattedString.length > 0 {
return String(formattedString)
}
else {
return detail
}
}
The NumberTool.far2cel() and NumberTool.cel2far() are my custom functions to convert between celsius and farehnheit.
Thoughts?
Hi, what do you think is wrong with the fucntion. This is what I have. Could it be because of the roundmode type used?
static func roundOff(_ val: String, _ decimalPlace: Int) -> String {
let decimalFormatter = createDecimalFormatter()
decimalFormatter.minimumFractionDigits = decimalPlace
decimalFormatter.maximumFractionDigits = decimalPlace
let bigDecimal = NSDecimalNumber(string: val)
return decimalFormatter.string(from: bigDecimal.rounding(accordingToBehavior: NSDecimalNumberHandler(roundingMode: .up, scale: Int16(decimalPlace), raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)))!
}
static func roundOff(_ value: Double, _ decimalPlace: Int) -> String {
return roundOff(String(value), decimalPlace)
}
roundOf("75.2", 0) returns 76 instead of 75
This is my current view. Instead of a List, I use a LazyVStack wrapped under a ScrollView.
.onAppear does not seem to work here. I assumed it runs when the view is visible on the screen.
My goal is when the footer is visible, it always runs a Task.
What could be wrong?
@State private var cities: [City]?
@State private var index = 0
@State private var showFooter = true
func content(_ cities: [City]) -> some View {
return GeometryReader { geometryProxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
if cities.count > 0 {
ForEach(cities) { city in
HStack {
Text(city.header)
.bold()
.foregroundColor(.white)
.textCase(.uppercase)
.padding(.all, 8)
Spacer()
}
.background(Color(UIColor(named: PrefTool.instance.getBoolean(Keyword.DARK_MODE) ? "DarkerGray" : "DarkGray")!))
ForEach(city.businesses) { busines in
Text(business.name)
Divider()
}
}
}
else {
Text("Empty List")
}
}
.safeAreaInset(edge: .bottom, spacing: 0) {
if showFooter {
VStack {
Text("Footer")
}
.padding()
.frame(maxWidth: .infinity)
// The background will extend automatically to the edge
.background(Color.green)
.onAppear {
Task {
do {
let moreList = try await getMoreCities(index)
showFooter = false
if !moreList.isEmpty {
cities?.append(contentOf: moreList)
showFooter = true
}
} catch {
showFooter = false
}
}
}
}
}
}
}
}
This is used inside body
var body: some View {
content(cities)
}
Thoughts? What is a good way to show a footer and then run a task when it is visible in the screen.
Hi . I am following the simple example from hacking with swift website. It is to request a location.
import CoreLocation
import CoreLocationUI
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
@Published var location: CLLocationCoordinate2D?
override init() {
super.init()
manager.delegate = self
}
func requestLocation() {
manager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("hehe")
location = locations.first?.coordinate
}
}
In the view. I have some custom button that when clicked, will call
locationManager.requestLocation()
but it gives this error message
Updates[14291:194102] *** Assertion failure in -[CLLocationManager requestLocation], CLLocationManager.m:1339
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Delegate must respond to locationManager:didFailWithError:'
*** First throw call stack:
(
0 CoreFoundation 0x0000000111b3a8cb __exceptionPreprocess + 242
1 libobjc.A.dylib 0x000000010d4efba3 objc_exception_throw + 48
2 Foundation 0x0000000116b3837c _userInfoForFileAndLine + 0
3 CoreLocation 0x000000010c1baf65 CLClientStopVehicleHeadingUpdates + 52782
7 SwiftUI 0x0000000113c6f5dc __swift_memcpy160_4 + 113486
8 SwiftUI 0x0000000113c6fe8d __swift_memcpy160_4 + 115711
9 SwiftUI 0x0000000113c6fdff __swift_memcpy160_4 + 115569
10 SwiftUI 0x00000001140a4270 objectdestroy.142Tm + 41347
11 SwiftUI 0x00000001140a4284 objectdestroy.142Tm + 41367
12 SwiftUI 0x00000001140a4270 objectdestroy.142Tm + 41347
13 SwiftUI 0x0000000113dba491 block_destroy_helper + 36990
14 SwiftUI 0x0000000113db9df2 block_destroy_helper + 35295
15 SwiftUI 0x0000000113f4b7a5 _callVisitToolbarContentType2 + 4011
16 SwiftUI 0x00000001146fa7c8 _callVisitStyleContextType2 + 11258
17 SwiftUI 0x00000001146f8e5e _callVisitStyleContextType2 + 4752
18 SwiftUI 0x00000001146f8f42 _callVisitStyleContextType2 + 4980
19 SwiftUI 0x00000001146f8720 _callVisitStyleContextType2 + 2898
20 UIKitCore 0x0000000120b384b9 -[UIGestureRecognizer _componentsEnded:withEvent:] + 153
21 UIKitCore 0x00000001211d7ebd -[UITouchesEvent _sendEventToGestureRecognizer:] + 662
22 UIKitCore 0x0000000120b286f7 -[UIGestureEnvironment _updateForEvent:window:] + 469
23 UIKitCore 0x000000012117aedb -[UIWindow sendEvent:] + 5282
24 UIKitCore 0x000000012114e7f2 -[UIApplication sendEvent:] + 898
25 UIKitCore 0x00000001211f5e61 __dispatchPreprocessedEventFromEventQueue + 9381
26 UIKitCore 0x00000001211f8569 __processEventQueue + 8334
27 UIKitCore 0x00000001211ee8a1 __eventFetcherSourceCallback + 272
28 CoreFoundation 0x0000000111a9a035 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
29 CoreFoundation 0x0000000111a99f74 __CFRunLoopDoSource0 + 157
30 CoreFoundation 0x0000000111a997d1 __CFRunLoopDoSources0 + 308
31 CoreFoundation 0x0000000111a93e73 __CFRunLoopRun + 927
32 CoreFoundation 0x0000000111a936f7 CFRunLoopRunSpecific + 560
33 GraphicsServices 0x000000011985b28a GSEventRunModal + 139
34 UIKitCore 0x000000012112d62b -[UIApplication _run] + 994
35 UIKitCore 0x0000000121132547 UIApplicationMain + 123
36 SwiftUI 0x00000001146b2cfb __swift_memcpy93_8 + 10826
37 SwiftUI 0x00000001146b2ba8 __swift_memcpy93_8 + 10487
38 SwiftUI 0x0000000113d68b7d __swift_memcpy195_8 + 12271
41 dyld 0x000000010be3d2bf start_sim + 10
42 ??? 0x0000000203a3d310 0x0 + 8651002640
)
libc++abi: terminating with uncaught exception of type NSException
Message from debugger: Terminated due to signal 6
I really have no clue what is going on. It does not enter some breakpoint, it just crashes. Anything I am missing?
Also, i could not find anything in the LocationManager regarding a callback when the location is retrieved? or it is a manual workaround that has to be done for this case?
the issue may be because i need to include the function
func locationManager(
_ manager: CLLocationManager,
didFailWithError error: Error
)
but adds another question. Why do i get Error Domain=kCLErrorDomain Code=1 "(null)"
All I have come across are NSURLSession. Is this possible for URLSession? How?
I noticed my requests show up instantly so I figured these reponses are cached instead of fetching new ones.
Caching should not be the default. Weird why it was set this way.
Thoughts?
This is my code. It is basic
let url = URL(string: urlLink)!
let (data, _) = try await URLSession.shared.data(from: url)
print(String(decoding: data, as: UTF8.self))
Hi, does anyone have some short code to display a marker with callout? There simply is no updated documentation of it. They are either using old names or I just have not found any tutorial of it.
I only found about MapMarker, but then it only shows a pin. on the map and no callout is possible.
This is what I have
Map(coordinateRegion: $mapRegion, showsUserLocation: true, annotationItems: markers) { marker in
marker.location
}
Where marker.location is MarkerMap. So it displays a pin correctly, but how to add a callout and link to it?
There are so many different names that start with MK. I am not sure if those are the latest. I figure MapAnnotation, MapMarker to name a few are the latest ones.
The various posts showing NSAttributedString rendering html tags has become mute because the bold tag does not work anymore.
Anyone know why? Or what the workaround is?
I am using this as the extension in string (found this in stackoverflow)
var htmlAttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: Data(utf8), options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
} catch {
return nil
}
}
var htmlString: String {
return htmlAttributedString?.string ?? ""
}
Bold just doesnt work. I do not see anything wrong with the code itself. It looks right. But it just does not render bold.
I read about adding style tag in the string with the default apple system font in it hardcoded, tried that but didnt work out still.
Regardless if I use a protocol or not that contains this method, e.g. I have this
var test: String?
func setupData() -> Void {
test = "New value"
}
Why does it say
Cannot assign to property: 'self' is immutable"
So if i add mutable to setupData() which becomes "mutating func setupData() { ... }", then i get another error message
Cannot use mutating member on immutable value: 'self' is immutable
I call setupData in onAppear() instead of init() for now. Putting it in init forces me to initialize the variables (sucks)
I am lost on this one. Advise?
This is used inside a Struct View. not a class.
I have the coordinate for northeast, southwest and center coordinates for a country Philippines
but it does not zoom in there. This is the code I am using in OnAppear in the map view
@State private var region = MKCoordinateRegion()
var body: some View {
Map(coordinateRegion: $region)
.edgesIgnoringSafeArea(.all)
.onAppear() {
region = MapTool.getPARCoordinateRegion()
}
}
static func getPARCoordinateRegion() -> MKCoordinateRegion {
let ph = getPHCountryPlaceMark()
let southWestPoint = MKMapPoint(x: ph.southWestLongitude, y: ph.southWestLatitude)
let northEastPoint = MKMapPoint(x: ph.northEastLongitude, y: ph.northEastLatitude)
let northWestPoint = MKMapPoint(x: southWestPoint.x, y: northEastPoint.y)
let mapRectWidth = northEastPoint.x - northWestPoint.x
let mapRectHeight = northWestPoint.y - southWestPoint.y
return MKCoordinateRegion(MKMapRect(x: southWestPoint.x, y: southWestPoint.y, width: mapRectWidth, height: mapRectHeight))
}
static func getPHCountryPlaceMark() -> CountryPlaceMark {
let countryPlaceMark = CountryPlaceMark()
countryPlaceMark.longName = "Philippines"
countryPlaceMark.shortName = "PH"
countryPlaceMark.centerLatitude = 12.879721
countryPlaceMark.centerLongitude = 121.774017
countryPlaceMark.southWestLatitude = 4.613444
countryPlaceMark.southWestLongitude = 116.931557
countryPlaceMark.northEastLatitude = 19.574024
countryPlaceMark.northEastLongitude = 126.604384
return countryPlaceMark
}
But instead zooms here. Thoughts?
Is this possible?
I have a class/struct that will store a function that will be used as an action to the button.
e.g.
struct Test {
var action: (() -> Void)?
}
This works
tempfunc() -> Void {
print("clicked it")
}
let test = Test()
test.action = tempfunc
Button("click me", action: test.action)
What I want to do is something like this.
test.action = () -> Void {
print("clicked")
}
Is this possible? If i try that code, error shows up saying "Cannot assign value of type '()' to type '() -> Void'"
Hi, is there a heatmap class that can be used in a SwiftUI Map? I do not want to use MKMapView and I have seen libraries that are not Swifty and does not make use of the new Map()
Tips are welcome on how to go about this? Or if anyone has a sample code?
I basically have an array of CLCoordinate2D and i wish to use that to generate a heatmap in the map.
No Google Maps please. I decidede not to use this since they do not have a SwiftUI version for it.
Hi. This is my MapView code
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
var region: MKCoordinateRegion
var polylineCoordinates: [CLLocationCoordinate2D]?
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
mapView.region = region
if let polylines = polylineCoordinates {
let polyline = MKPolyline(coordinates: polylines, count: polylines.count)
mapView.addOverlay(polyline)
}
return mapView
}
func updateUIView(_ view: MKMapView, context: Context) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
}
class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
let routePolyline = overlay as! MKPolyline
let renderer = MKPolylineRenderer(polyline: routePolyline)
renderer.strokeColor = UIColor.white
renderer.lineWidth = 2
return renderer
}
return MKOverlayRenderer()
}
}
If i do this
var body: some View {
MapView(region: [array of CLLocationCoordinage2D])
.edgesIgnoringSafeArea(.all)
}
it works since the value of the region property is set in the constructor. However, what i want is to set the region property in the onAppear closure. What is lacking here since it does not work.
I wish to do something like this
var body: some View {
MapView(region: region)
.edgesIgnoringSafeArea(.all)
.onAppear {
region = [array of CLLocationCoordinage2D]
}
}
I want to apply the same thing to polylineCoordinates property but for now, if I can make it work with region, I am sure the same thing can be applied to polylineCoordinates property.
Thoughts?
Hi, beginner here. So I have read how 1 way to use an optional without having to be forced to unwrap it with ! is this ...
if let var1 = optionalVar1 {
}
This is not a prob. But what if i have too many optionals? I do not want to have nested if let blocks. Is there a shorter way not to do too many ifs that without having to unwrap it with ! ?
e.g.
if let var1 = optionalVar1 {
if let var2 = optionalVar2 {
if let var3 = optionalVar3 {
}
}
}