I'm trying to animate a shape. The following is my code.
import SwiftUI
struct ContentView7: View {
@State private var goingLeft = true
@State private var goingUp = true
var body: some View {
ZStack {
Color.green.ignoresSafeArea()
CustomShape(quadDistance: goingUp ? 0: 60.0, horizontalDeviation: 0.0)
.fill(Color.red)
.ignoresSafeArea()
.animation(.easeInOut(duration: 1.0).repeatForever(), value: goingUp)
}.onAppear {
goingUp = false
}
}
}
struct CustomShape: Shape {
var quadDistance: CGFloat
var horizontalDeviation: CGFloat
func path(in rect: CGRect) -> Path {
Path { path in
path.move(to: CGPoint(x: -horizontalDeviation, y: 0))
path.addLine(to: CGPoint(x: rect.maxX + horizontalDeviation , y: 0))
path.addLine(to: CGPoint(x: rect.maxX + horizontalDeviation, y: rect.midY))
path.addLine(to: CGPoint(x: -horizontalDeviation, y: rect.midY))
path.move(to: CGPoint(x: -horizontalDeviation, y: rect.midY))
path.addQuadCurve(to: CGPoint(x: rect.maxX + horizontalDeviation, y: rect.midY), control: CGPoint(x: rect.midX, y: rect.midY + quadDistance))
}
}
}
Well, my intension is to move the center of the convex point up and down. But the shape won't animate itself. What am I doing wrong? Muchos thankos.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I am just playing with NSTextList by creating a sample iOS app. The following is my code.
import UIKit
class ViewController: UIViewController {
lazy var textView: UITextView = {
let textView = UITextView()
textView.text = ""
textView.contentInsetAdjustmentBehavior = .automatic
textView.backgroundColor = .white
textView.font = UIFont.systemFont(ofSize: 20.0)
textView.textColor = .black
textView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
textView.widthAnchor.constraint(equalToConstant: 600.0),
textView.heightAnchor.constraint(equalToConstant: 600.0)
])
return textView
}()
lazy var button: UIButton = {
let button = UIButton()
button.setTitle("End list", for: .normal)
button.setTitleColor(.white, for: .normal)
button.setTitleColor(.lightGray, for: .highlighted)
button.backgroundColor = .black
button.layer.cornerRadius = 8.0
button.addTarget(self, action: #selector(fixTapped), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.widthAnchor.constraint(equalToConstant: 100.0),
button.heightAnchor.constraint(equalToConstant: 42.0)
])
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBlue
view.addSubview(textView)
view.addSubview(button)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tapGesture)
NSLayoutConstraint.activate([
textView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
textView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
NSLayoutConstraint.activate([
button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20.0)
])
let list = NSTextList(markerFormat: .diamond, options: 0)
list.startingItemNumber = 1
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.textLists = [list]
let attributes = [NSAttributedString.Key.paragraphStyle: paragraphStyle, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 24.0)]
let attributedStr = NSMutableAttributedString(string: "\n\n\n\n\n", attributes: attributes)
textView.textStorage.setAttributedString(attributedStr)
}
@objc func fixTapped() {
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
When the app launches itself, I get 5 lines of diamond guys as shown in the following screenshot.
If I keep pressing the delete key with a connected keyboard, the list will be gone as shown below.
But if I press the RETURN key several times, the diamond list will come back as shown below.
So how can I end this June TextList madness? In code, I have the dismissKeyboard function if I can end this madness programmatically.
Thanks,
Señor Tomato Spaghetti
Chief Janitor at
Southeastern Tomato Spaghetti Trade Association
I've been trying to save a selected color with UserDefaults from UIColorPickerViewController. But I run into a color space fiasco. Anyway, here come my lines of code.
class ViewController: UIViewController, UIColorPickerViewControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBAction func selectTapped(_ sender: UIButton) {
let picker = UIColorPickerViewController()
picker.delegate = self
picker.selectedColor = .yellow
picker.supportsAlpha = false
present(picker, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let color = UserDefaultsUIColor.shared.readColor(key: "MyColor") {
print("Color being read: \(color)")
}
}
func colorPickerViewControllerDidFinish(_ viewController: UIColorPickerViewController) {
let color = viewController.selectedColor
print("Selected color: \(color)")
UserDefaultsUIColor.shared.saveColor(color: viewController.selectedColor, key: "MyColor")
}
func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
imageView.backgroundColor = viewController.selectedColor
}
}
class UserDefaultsUIColor {
static let shared = UserDefaultsUIColor()
func saveColor(color: UIColor, key: String) {
let userDefaults = UserDefaults.standard
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: false) as NSData?
userDefaults.set(data, forKey: key)
} catch {
print("Error UserDefaults: \(error.localizedDescription)")
}
}
func readColor(key: String) -> UIColor? {
let userDefaults = UserDefaults.standard
if let data = userDefaults.data(forKey: key) {
do {
if let color = try NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: data) {
return color
}
} catch {
print("Error UserDefaults")
}
}
return nil
}
}
I first start out with a yellow color (UIColor.yellow). And I select a color whose RGB values are 76, 212, 158, respectively. And the color picker guy returns the following.
kCGColorSpaceModelRGB 0.298039 0.831373 0.619608 1
And I get the following in reading the saved color data object.
UIExtendedSRGBColorSpace -0.270778 0.84506 0.603229 1
How can I save and read color data objects consistently? I could specify a color space when I save a color. But it doesn't go well.
Muchos thankos
Señor Tomato de Source
Oh, boy... Xcode has become more and more difficult to deal with. Today, I've dowloaded Version 15.0 beta 4. It took my 2019 iMac with 64 GB of RAM some 20 minutes just to launch an iPhone 14 Simulator and to let me see the home screen. Xcode takes 3 or 4 minutes to run code after I change just one line. I only have some 30 lines of code in total. It's a truly disappointing update. I wish they stop adding unnecessary features like code-folding animation to slow things down.
import UIKit
class ViewController: UIViewController {
private let photoView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(systemName: "airplane")
//imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemYellow
view.addSubview(photoView)
NSLayoutConstraint.activate([
photoView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
photoView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
photoView.widthAnchor.constraint(equalToConstant: 200),
photoView.heightAnchor.constraint(equalToConstant: 200)
])
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.runAirplaneAnimation()
}
}
func runAirplaneAnimation() {
photoView.addSymbolEffect(.pulse, animated: true)
}
}
I have the following lines of code to list some music titles from iTunes music. The code is 100% reproducible.
import SwiftUI
struct MusicView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
MusicListView(viewModel: viewModel)
}
}
struct MusicListView: View {
@ObservedObject var viewModel: ViewModel
var body: some View {
NavigationView {
List(viewModel.results, id: \.self) { result in
VStack(alignment: .leading) {
Text("Track ID: \(result.trackId)")
Text("Track name: \(result.trackName)")
}
}
.task {
do {
try await viewModel.fetchMusic()
} catch SessionError.badURL {
print("Bad URL")
} catch SessionError.invalidHTTPResponse {
print("Invalid HTTP response")
} catch SessionError.error(let err) {
print("Error: \(err)")
} catch {
print("\(error.localizedDescription)")
}
}
.navigationTitle("Music")
}
}
}
class ViewModel: ObservableObject {
@Published var results: [Result] = []
func fetchMusic() async throws {
guard let url = URL(string: "https://itunes.apple.com/search?term=classical+music&entity=song") else {
throw SessionError.badURL
}
let urlRequest = URLRequest(url: url, timeoutInterval: 0.00) // <<<<<<<<<<<<<
URLSession.shared.dataTask(with: urlRequest) { data, response, error in
do {
guard let data = data, error == nil else {
throw SessionError.noData
}
guard let httpResponse = response as? HTTPURLResponse else {
throw SessionError.invalidHTTPResponse
}
switch httpResponse.statusCode {
case 200:
let res = try JSONDecoder().decode(Response.self, from: data)
DispatchQueue.main.async {
self.results = res.results
}
case 400...499:
throw SessionError.badURL
default:
fatalError()
break
}
} catch {
print(error.localizedDescription)
}
}
.resume()
}
}
struct Response: Codable {
let resultCount: Int
let results: [Result]
}
struct Result: Codable, Hashable {
var trackId: Int
var trackName: String
var collectionName: String
}
enum SessionError: Error {
case badURL
case noData
case decoding
case invalidHTTPResponse
case badRequest(statusCode: Int)
case redirection(statusCode: Int)
case server(statusCode: Int)
case error(String)
}
As you see in the screenshot, I get some music titles listed.
My question is why I get a list when in fact I have the URLRequest's timeout value set to 0.00? I haven't run it with an actual device. As far as I use an iPhone simulator, regardless of the timeout value that I set, I get data downloaded. I wonder why?
Muchos thankos for reading
I have a macOS application developed in SwiftUI. It's a document-based application. I know how to hide the Show Tab Bar command under View. I don't want to hide it. I always want to show tabs. I wonder how to enable this command programmatically such that the document window always has the + button to the right. Thanks.
I've submitted my first AR app for iPhone and iPad to iTunes Connect. After sending a binary to iTunes Connect, I've received the following warning message.
The app contains the following UIRequiredDeviceCapabilities values, which aren’t supported in visionOS: [arkit].
No. 1, my app doesn't support visionOS. No. 2, I don't have the UIRequiredDeviceCapabilities dictionary in info.plist. Why am I receiving this warning? One article related to this issue that I've read suggests that I remove the UIRequiredDeviceCapabilities dictionary. Well, I don't have it in my plist. What can I do with this warning message? Thanks.
Topic:
Spatial Computing
SubTopic:
ARKit
A few weeks ago, I explored the possibility of installing auto-renewal subscription plans on an iOS app. Initially, I thought subscription plans are allowed for news and magazine apps. Then I saw this Apple website, which actually encourages us to provide 'free, limited access to app content.' So I took their advice and submitted an iOS app that has no dynamic content to App Store. I submitted another. Two apps have been approved. And I have got the third one put on hold several days ago. The reviewer has asked me an uncomfortable line of questions repeatedly like
What are changes?
How often?
that I have never received in my 13 or 14 year history. Then he or she rejected it two days ago. And I got a 4th one approved at the same time. So three are admitted in with one rejected.
Does an app have to have dynamic content to use auto-renewal subscription plans? I don't find any statement in Apple Review Guidelines that prohibits me from installing auto-renewal subscription plans on non-dynamic content app. There are other big-time apps like Microsoft 365 and Adobe Photoshop that are available with subscription plans. I am very perplexed.
I have a SwiftUI view with a button. I want to open a window sheet from a storyboard. Showing a window sheet isn't a problem. It's just that the application no longer has a menu bar. As soon as I created a storyboard and a view controller (NSViewController), the application stopped showing up properly. Now, if I try to debug it (Command + R), the window won't appear. So I have to click on the Live Preview button on the Canvas. If I do, I can click on the Bring Forward button. Finally, if I click on it, the application window always appears at the bottom-left corner of the desktop without the menu bar. So what's the issue?
Anyway, the following is my code.
// SwiftUI View //
import SwiftUI
struct ContentView: View {
		@State private var sheetPresented = false
		@State private var selectionIndex = 3
		
		var body: some View {
				ZStack {
						VStack {
								Button(action: {
										sheetPresented = true
								}) {
										Text("Show me a sheet")
								}
								.sheet(isPresented: $sheetPresented) {
										SheetViewControllerRepresentation(message: String(selectionIndex))
								}
						}
				}.frame(minWidth: 360, idealWidth: 360, maxWidth: 360, minHeight: 240, idealHeight: 240, maxHeight: 240, alignment: .center)
		}
}
// View controller //
import Cocoa
import SwiftUI
class SheetViewController: NSViewController {
		// MARK: -
		var message = String()
		
		
		// MARK: - IBOutlet
		@IBOutlet weak var messageLabel: NSTextField!
		
		
		// MARK: - Life cycle
		override func viewDidLoad() {
				super.viewDidLoad()
				// Do view setup here.
		}
		
		override func viewWillAppear() {
				super.viewWillAppear()
				
				messageLabel.stringValue = message
		}
		
		override func viewDidAppear() {
				super.viewDidAppear()
				
				view.setFrameSize(CGSize(width: 320, height: 220))
		}
}
struct SheetViewControllerRepresentation: NSViewControllerRepresentable {
		var message = String()
		
		func makeNSViewController(context: NSViewControllerRepresentableContext<SheetViewControllerRepresentation>) -> SheetViewController {
				let mainStoryboard = NSStoryboard(name: "Main", bundle: nil)
				let sheetViewController = mainStoryboard.instantiateController(withIdentifier: "SheetView") as! SheetViewController
				sheetViewController.message = self.message
				return sheetViewController
		}
		
		func updateNSViewController(_ nsViewController: SheetViewController, context: NSViewControllerRepresentableContext<SheetViewControllerRepresentation>) {
		}
}
Thank you.
Let me suppose that I have an Xcode project that uses the following Cocoapods.
	pod 'Firebase/Auth'
	pod 'GoogleSignIn'
And let me also suppose that the minimum deployment target for my Xcode project is 11.0. In this case, do I set the Cocoapod platform to 11.0 like
platform :ios, '11.0'
target 'MyProject' do
	use_frameworks!
	pod 'Firebase/Auth'
	pod 'GoogleSignIn'
end
Or do I use the latest versions of Cocoapods like
platform :ios, '14.2'
target 'MyProject' do
	use_frameworks!
	pod 'Firebase/Auth'
	pod 'GoogleSignIn'
end
?
Thanks.
When you develop an iOS app for some company, say Company A, under whose name should you sign up a developer account so that you can code-sign the app and send it to the iTunes Connect server? Is it you or Company A? I am thinking that I can sign up a new account to submit an app as long as I give the copyright to Company A. My concern is that there was a new rule like Spamming that took effect several years ago. I guess some guys were using the same package and only changed superficial aspects to submit a ton of similar apps. Thanks.
p.s. It's not an in-house app under an enterprise account that I'm talking about. The app will be submitted to the App Store.
Hello. I'm a little bit confused about how TestFlight works. If I have an iOS app under development that has not been in the store and that has not been submitted for a review yet, can I use TestFlight to have it tested by my development team? I know that there are two types of tests, internal tests and external tests. It seems that you can use TestFlight for internal tests even if the app has not been submitted for a review. Thanks.
I just want to show a simple navigation title like the following.
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
ZStack {
Color.red.edgesIgnoringSafeArea(.all)
Text("Hello")
}
.navigationTitle("GGG")
.navigationBarTitleDisplayMode(.inline)
.navigationBarHidden(false)
}
}
}
And I get a bunch of mumbo jumbo auto-layout warnings (Unable to simultaneously satisfy constraints...) in Console. If I comment out the navigationTitle line, I won't get them. I have never seen those messages in showing a navigation title when writing code with UIKit. What am I doing wrong? Muchos thankos
I have the following lines of code to work with a list of strings.
import SwiftUI
struct ContentView: View {
@State private var users = ["George", "Kenny", "Susan", "Natalie"]
var body: some View {
NavigationView {
List {
ForEach(users, id: \.self) { user in
Text(user)
}
.onDelete(perform: delete)
}
.navigationBarTitle("My family")
.toolbar {
EditButton()
}
}
}
func delete(at offsets: IndexSet) {
users.remove(atOffsets: offsets)
}
}
Now, I'm doing the following out of curiosity. Now, I have a button in naviationBarItems. And I wonder if I can turn on and off the edit feature of the list with the button?
struct ContentView: View {
@State private var users = ["George", "Kenny", "Susan", "Natalie"]
var body: some View {
NavigationView {
List {
ForEach(users, id: \.self) { user in
Text(user)
}
}
.navigationBarTitle("My family")
.navigationBarItems(trailing:
Button(action: {
print("Edit button pressed...")
}) {
Text("Edit")
}
)
}
}
}
Muchos thankos.
I'm playing with @EnvironmentObject to see how it works in SwiftUI. I have the main view (ContentView) where it says the user has not logged in yet. By letting the user tap a link, I want to make it such that they can log in by tapping a button.
class LoginMe: ObservableObject {
@Published var loggedIn = false
}
struct ContentView: View {
@StateObject var loginMe = LoginMe()
var body: some View {
if loginMe.loggedIn {
Text("Yes, I'm logged in")
} else {
NavigationView {
VStack {
Text("No, not logged in yet")
.padding(.vertical)
NavigationLink(destination: LoginView()) {
Text("Tap to log in")
}
}
.navigationBarTitle("User")
}
.environmentObject(loginMe)
}
}
}
struct LoginView: View {
@EnvironmentObject var loginMe: LoginMe
var body: some View {
/*
Toggle(isOn: $loginMe.loggedIn) {
Text("Log in")
}.padding(.horizontal)
*/
Button("Login") {
loginMe.loggedIn.toggle()
}
}
}
So far, when the user taps a button in the LoginView view, the screen goes back to ContentView and the navigation simply disappears. How can I change my code so that the status will change back and forth in in the LoginView view by tapping a button and then so that they can return to ContentView the navigation return button? I think the problem is that I need to use @State var in ContentView and @Binding var in LoginView. Things are kind of confusing. Muchos thankos.