I want to use pencil kit in my swiftui app. I encapsulate PKCanvasView in UIViewRepresentable. I can draw on canvas with only one stroke. However, the image will disappear immediately when I release the finger.
Am I missing anything?
import SwiftUI
import PencilKit
struct ContentView: View {
var body: some View {
CanvasView()
}
}
struct CanvasView: UIViewRepresentable {
func makeUIView(context: Context) -> PKCanvasView {
let canvas = PKCanvasView()
canvas.tool = PKInkingTool(.pen, color: .green, width: 10)
canvas.drawingPolicy = .anyInput
return canvas
}
func updateUIView(_ uiView: PKCanvasView, context: Context) {
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
[https://developer.apple.com/fonts/system-fonts/) shows dozens of system fonts. And it says "Apple platforms come with many preinstalled fonts that can be used by your app’s user interface. " on the top of the web page. Does it mean I can use any of them in my iOS app legally? Does it involve font license issue? What else should I pay attention to use system fonts legally?
According to the documentation of ".offset", The original dimensions of the view aren’t changed by offsetting the contents; in the example below the green border drawn by this view surrounds the original position of the text:
Text("Hello, World!")
.border(Color.black)
.offset(x: 10.0, y: 50)
.border(Color.green)
IMO, the modifer (ie,.border(Color.green))followed ".offset" should only affect the original view, but not the new view.
When add a ".frame" right after the ".offset", I thought it also only affect the original view. However, the original and the new view are both affected.
Text("Hello, World!")
.border(Color.black)
.offset(x: 10.0, y: 50)
		.frame(width:50)
.border(Color.green)
Further more, if I keep adding another ".frame" right after the first one, only the original view is affected again.
Text("Hello, World!")
.border(Color.black)
.offset(x: 10.0, y: 50)
.frame(width:50)
.frame(width:100)
.border(Color.green)
What happened under the hood? Thanks in advanced.
I want to demonstrate a large size image(5184*3456) in a modal sheet with swiftui.
When I popup the sheet, memory usage increases from 20mb up to 100mb. However, when I dismiss the sheet, memory usage just decreases from 100mb to 92mb, wear and tear. I popup the sheet again, memory usage increases from 92mb back to 100mb.
Back and forth, memory usage always changes between 92mb and 100mb, instead of between 20mb and 100mb that I expect to. Why doesn't memory usage decrease to 20mb when the sheet dismiss? Why doesn't image been purged from memory when the sheet dismisses? I just want memory usage stays in a low level. How could I do? Thanks in advance.
struct IntroductionView: View {
@Environment(\EnvironmentValues.presentationMode) var presentation
var body: some View {
GeometryReader{geo in
VStack(alignment:.leading){
Image("image")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(maxHeight:geo.size.height/4)
.clipped()
Spacer()
Button(action: {
presentation.wrappedValue.dismiss()
}, label: {
Text("Close")
}
}
}
}
}
I want to set "ringer and alerts" sound in code.
MPVolumeView() seems like to control the system volume only. I have some sound effect(by invoking "AudioServicesPlaySystemSound(SystemSoundID:)") affected by "ringer and alerts" in my app. Even when the system volume is max, my app sound effect is still mute if "ringer and alerts" sound is mute. I have to tune "ringer and alerts" by "setting-sounds-ringer and alerts" manually.
Is there any programable way to set it? Any help will be greatly appreciated.
I know I can use .redacted(reason: .placeholder) to make displayed data appear as generic placeholders. But how can I declare a custom RedactionReasons instance and use it? The examples of initializer in documentation seem not to be helpful. Thanks in advance.
I have an app released in the iOS store which is set to be price tier 1. I want to set it to be free for just next week. After that, the price should be back to price tier1 again. If I
tune it in App Store connect. Will it make my app to be in review again, or just take effect immediately? Thanks in advance.
Topic:
App Store Distribution & Marketing
SubTopic:
App Store Connect
Tags:
App Review
App Store
App Store Connect
struct ContentView: View {
@State private var num = 0
var body: some View {
VStack{
Text(String(num))
.padding()
Button(action: {
num += 1
}, label: {Text("click+1")})
}
}
}
Question 1:
If I run the code above on simulator, I could get the value of "num" on the console by using"po _num".
However, if I run the code in previews(by "Debug-Attach to process"), I only get the error"error: :3:1: error: cannot find '_num' in scope" on the console by using"po _num"
Xcode 13.2.1
Question 2:
I could use "po num"/"po _num" to get the value of "num" with Xcode 12.
BUT, only "po _num" works in Xcode13. "po num" will raise the error:"
error: Couldn't lookup symbols: Preview2.ContentView.num.getter : Swift.Int"
Any help will be appreciated.
I make a toggle to control a textfield in a form. When I run it, I get a piece of warning:
invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution
What could I do to fix it? What's the harm if it's not fixed( App crashes, or...?). Any help will be appreciated.
struct ContentView: View {
@State private var toggle1 = true
@State private var str1 = "..."
var body: some View {
Form{
Section{
Toggle(isOn: $toggle1, label: {
Text("Toggle 1")})
}
Section{
if toggle1{
HStack{
Text("Toggle 1")
TextField("...", text: $str1)
}
}
}
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
}
I have two lists side-by-side. I want to scroll any one of the lists, and the other one can scroll synchronously. Is there any way to achieve the effect? Any help will be appreciated.
struct ScrollTwoListsSynchronously: View {
let dataSet = [1,2,3,4,5]
var body: some View {
HStack{
List{
ForEach(dataSet,id:\.self){data in
Text(String(data))
}
}
.listStyle(PlainListStyle())
List{
ForEach(dataSet,id:\.self){data in
Text(String(data))
}
}
.listStyle(PlainListStyle())
}
}
}
I have a list to show some records. A weird issue will happen as follow steps:
--tap "insert" button for some times(eg. 3 times)
--swipe a record from right to left to delete it
--tap "edit" button to switch to edit mode
--tap "insert" button to insert a new record
The first 2 records both have a "option button"(a small hollow circle). BUT the last inserted record has no "option button". The list seems like to reuse the view of the deleted record in "non-edit" mode. All of the 3 records can be selected by click. I wonder how to make the inserted record to also have a "option button".
struct ListEditModeSubviewUpdateTest: View {
@State private var data = [Int]()
@State private var editMode = EditMode.inactive
@State private var selects = Set<Int>()
@State private var base = 0
var body: some View{
VStack{
Button {
if editMode.isEditing{
editMode = .inactive
}else{
editMode = .active
}
} label: {
Text(editMode.isEditing ? "Done" : "Edit")
}
Button {
base += 1
data.append(base)
} label: {
Text("Insert")
}
List(selection: $selects){
ForEach(data, id:\.self){item in
Text(String(item))
}
.onDelete{
data.remove(atOffsets: $0)
}
}
}
.environment(\.editMode, $editMode)
}
}
I need to use some "uikit view controller" in my swiftui app. I have encapsulate the vc in a representable view. It works well. However, the background color will extend outside of safe area when I rotate the simulator from portrait to landscape and back to portrait.
I want the background color always to stay inside safe area. I prototype a sample code to illustrate the issue.
struct ContentView: View {
var body: some View {
ZStack{
Color.gray
CustomRepresentation()
}
}
}
struct CustomRepresentation: UIViewControllerRepresentable{
func makeUIViewController(context: Context) -> some UIViewController {
return UIViewController()
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
}
If I comment the CustomRepresentation(), the gray color will stay inside the safe area all the time during rotating. So I realize the key point is CustomRepresentation(). But I don't know how to fix it.
I write some code to show an image dragged from other apps(such as web browser, photos, etc). I make a delegate to perform the drop.
If DropInfo has an image item, I will try to retrieve the data as uiimage by NSItemProvider.loadObject first. If errors occur during loading, I will ask DropInfo again whether it has a url item. If the answer is YES, I will try to retrieve URL by NSItemProvider.loadObject.
It means the second loadObject will be nested in the first one. When running the simulator, I find the second loadObject completion handler is never called which is supposed to be called when I try to retrieve URL. Do I miss anything?
import SwiftUI
import Combine
struct ContentView: View{
@State private var img: UIImage?
var body: some View{
Image(uiImage: img != nil ? img! : UIImage(systemName: "photo")!)
.resizable()
.scaledToFit()
.onDrop(of: [.image], delegate: ImageDropController(img: $img))
}
}
class ImageDropController: DropDelegate{
@Binding var img: UIImage?
init(img: Binding<UIImage?>) {
_img = img
}
func performDrop(info: DropInfo) -> Bool {
if getImgFromImage(info: info){
return true
}else{
return false
}
}
func getImgFromImage(info: DropInfo) -> Bool{
guard info.hasItemsConforming(to: [.image]) else {
return getImgFromUrl(info: info)
}
createImgFromImage(from: info.itemProviders(for: [.image]).first!,info: info)
return true
}
func createImgFromImage(from provider: NSItemProvider, info: DropInfo){
provider.loadObject(ofClass: UIImage.self) { image, error in
var unwrappedImage: UIImage?
if let error = error {
print("unwrapImage failed: ", error.localizedDescription)
_ = self.getImgFromUrl(info: info)
} else {
unwrappedImage = image as? UIImage
}
if let image = unwrappedImage{
DispatchQueue.main.async {
self.img = image
}
}
}
}
func getImgFromUrl(info: DropInfo) -> Bool{
guard info.hasItemsConforming(to: [.url]) else {
return false
}
createImgFromUrl(from: info.itemProviders(for: [.url]).first!)
return true
}
private func createImgFromUrl(from provider: NSItemProvider){
var fetchUrl: URL?
print("create from url")
_ = provider.loadObject(ofClass: URL.self) { url, error in
print("nested handler") <<------- never be called
if let error = error {
print("unwrapUrl failed: ", error.localizedDescription)
} else {
fetchUrl = url
print("url", fetchUrl?.description)
}
if let url = fetchUrl{
// Do some data fetch work using url
}
}
}
}
I write some code to drag a photo from external app to a rectangle area in my app. I want to achieve an effect that the rectangle changes to semitransparent when the photo is dragged inside the rectangle without release. And then the rectangle changes back to opacity when the photo is dragged outside of the rect area.
I put my app and Photos side by side where my app is on the left side. If I drag the photo in and out from right side, it works good. However, the dropExited method is never called, if I drag the photo out from the left side. The result is the rect stays in semitransparent.
It seems like the drag gesture is considered to cancel automatically INSTEAD of drop exits the area because of touching the screen border. What should I do to reset the rect to opacity in this case?
import SwiftUI
struct ContentView: View {
@State private var dragIn = false
var body: some View {
VStack {
Rectangle()
.foregroundColor(.gray)
.opacity(dragIn ? 0.5 : 1)
}
.onDrop(of: [.image], delegate: DropController(dragIn: $dragIn))
}
}
class DropController: DropDelegate{
@Binding var dragIn: Bool
init(dragIn: Binding<Bool>) {
_dragIn = dragIn
}
func dropExited(info: DropInfo) {
dragIn = false
print("out")
}
func dropUpdated(info: DropInfo) -> DropProposal? {
dragIn = true
print("dragging")
return nil
}
func performDrop(info: DropInfo) -> Bool {
true
}
}
I want to drag the image along y-axis. It seems quite simple. However I put the "offset" following the "gesture" by mistake. Then cpu runs at full speed and UI becomes irresponsive.
Everything is ok by reordering "offset" before "gesture". But I can't figure it out.
"DragEffectViewModifier-ondrag" displays on the console repeatedly. What leads to the "cycle behavior"? It makes cpu to run at full speed and UI to become irresponsive when "offset" placed below "gesture"
struct ContentView: View {
@State private var currentPosition: CGSize = .zero
@State private var newPosition: CGSize = .zero
var body: some View {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
// .offset(x: currentPosition.width, y: currentPosition.height)
.gesture(DragGesture()
.onChanged { value in
print("DragEffectViewModifier-ondrag")
currentPosition = CGSize(width: 0, height: value.translation.height + newPosition.height)
}
.onEnded { value in
newPosition = currentPosition
})
.offset(x: currentPosition.width, y: currentPosition.height)
}
}