I want to get the loop times info in playground. But it seems to only display the latest result for a loop on the right side. Do I miss anything? Xcode 15.0.1
import Cocoa
for i in 1...5{
print("\(i)")
}
I have a screenshot:
Post
Replies
Boosts
Views
Activity
I'm creating a launch screen by storyboard for a swiftui app. When I rotate the iPhone 14 to landscape, the safe area has insets on vertical, without any inset on horizontal(shown as the image below). IMO, the safe area should have inset on leading, trailing and bottom edge in this case. Do I miss anything?
[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?
I need to use custom font in my app. While the built-in standard font will align in center automatically, the custom font seems to align "top"(seeing red border part) instead of "center"(blue border part). Is there any approach to fix it?
struct ContentView: View {
var body: some View {
VStack(spacing: 20){
Text("SEPTEMBER")
.font(.largeTitle)
.border(.blue)
Text("SEPTEMBER")
.font(Font.custom("Arial Hebrew", size: 20))
.border(.red)
}
}
}
I need use a built-in text editor, a custom text editor and a built-in text field in the same list. I encounter a couple of problems:
set font to .body: The row height of custom text editor is bigger than the other two. The custom text editor can't stay in the center of the row by vertical. The text editor can't align to text field by leading.
set font to .title: In addition to problem 1 behavior, the built-in text editor can't stay in the center of the row by vertical either.
How could I make the three components to have the same row height and align center in vertical and align by leading?
struct ContentView: View {
@State private var text = "hello"
@State private var text2 = ""
var body: some View {
List{
Section("title"){
CustomTextEditor(text: $text)
TextEditor(text: $text)
.font(.title)
TextField("hello", text: $text2)
.font(.title)
}
}
}
}
struct CustomTextEditor: UIViewRepresentable{
@Binding var text: String
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.isScrollEnabled = false
textView.font = UIFont.preferredFont(forTextStyle: .title1)
textView.text = text
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
}
}
I am practising matchedGeometryEffect.
struct ContentView: View {
@Namespace var tem
@State var isTemp: Bool = true
var body: some View{
ZStack{
if isTemp{
Circle()
.matchedGeometryEffect(id: "haha", in: tem, anchor: .center)
.foregroundColor(.green)
.frame(width: 200, height: 200)
}else{
Rectangle()
.matchedGeometryEffect(id: "haha", in: tem, anchor: .center)
.foregroundColor(.blue).opacity(0.4)
.frame(width: 400, height: 600)
}
Button {
withAnimation(.linear(duration: 5)){
isTemp = false
}
} label: {
Text("switch")
}
}
}
}
If I set anchor to top, it works well with the tops of both shapes remaining alignment.
When I set anchor to center, I expect both shapes should stay at the center point of screen and extend around. However, only the rectangle stays still as expected, while the circle descends like bottom anchor effect.
What's more, if I set anchor to bottom, the circle descends more quickly. Is it a normal behavior? Do I miss anything?
I have a swiftui view that displays a picture which users select from Photo app and shows some texts below the picture. I want to dynamically tune the background color of the view depending on the picture major color. Say, if users select a grass or forest image, the background auto changes to green. Is there any best practice?
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)
}
}
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) {
}
}
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 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'm writing an app which allow users to pick images from photo library by swiftUI. I wrap PHPickerViewController in representable to achieve the functionality. The benefit is that users don’t need to explicitly authorize my app to select photos.
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult])
Currently, I get images by picker(::) method above and save images in my app in order to reload images the next time users launch the app without needs to request authorization.
Obviously, if the app stores references to the selected images, rather than images themselves, it can prevent from taking up large amounts of space. Is it meaning that I have to prompt to users for requesting authorization to access the library? Is there any approach only to use references and reload images which were selected by users previously from photo library using PHPickerViewController, supporting no need to request authorization.
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 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 have a list. When I click the show button in any of rows, the long text appears and the height of row auto gets taller enough to show all of the long text.
However, when the list is in "edit" mode, the height of row can't auto get taller enough to show all of the long text. The long text is truncated. I have to push the list to the top manually and release, then the height of row auto gets taller and the long text can be completely displayed again. Is there any way to achieve the "auto" adjustment effect just the same as the "non-edit" mode?
struct ListEditTest: View {
@State private var selects: Set<Int> = []
var body: some View {
VStack{
EditButton()
List(selection: $selects){
ForEach(1..<5){
ItemInList(num: $0)
}
}
.listStyle(PlainListStyle())
}
}
}
struct ItemInList: View{
let num: Int
@State private var showDetail = false
var body: some View{
HStack{
Text("NO.\(num)")
Text("HelloWorld")
if showDetail{
Text("TooManyWordsTooManyWordsTooManyWordsTooManyWordsTooManyWordsTooManyWordsTooManyWordsTooManyWords")
Button {
showDetail.toggle()
} label: {
Text("Hide")
}
}else{
Button {
showDetail.toggle()
} label: {
Text("Show")
}
}
}
.buttonStyle(BorderlessButtonStyle())
}
}