我正在尝试使用swift以编程方式创建一个简单的tableView,所以我在"AppDelegate.swift"上编写了这段代码:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
var tvc :TableViewController = TableViewController(style: UITableViewStyle.Plain)
self.window!.rootViewController = tvc
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
return true
}
Run Code Online (Sandbox Code Playgroud)
基本上我添加了TableViewController创建并添加到窗口.这是TableViewController代码:
class TableViewController: UITableViewController {
init(style: UITableViewStyle) {
super.init(style: style)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return 1
} …Run Code Online (Sandbox Code Playgroud) 我正在使用CoreData测试swift,我创建了以下代码:
import UIKit
import CoreData
class Contact: NSManagedObject {
@NSManaged var name: String
@NSManaged var email: String
class func execute(){
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext!
let entityDescripition = NSEntityDescription.entityForName("Contact", inManagedObjectContext: context)
let contact = Contact(entity: entityDescripition!, insertIntoManagedObjectContext: context)
contact.name = "john Apleesee"
contact.email = "john@apple.com"
context.save(nil)
let fetch:NSFetchRequest = NSFetchRequest(entityName: "Contact")
var result = context.executeFetchRequest(fetch, error: nil) as [Contact]
let firstContact = result[0] as Contact // <<-- error !
println("\(firstContact.name)")
println("\(firstContact.email)")
}
}
Run Code Online (Sandbox Code Playgroud)
当我跑:
Contact.execute() …Run Code Online (Sandbox Code Playgroud) 我想UIImageView在里面添加一个动画,UICollectionViewCell所以我想出了这段代码:
import UIKit
class MainViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var items:[String] = ["one", "two", "three", "four"]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1.0)
self.view.addSubview(self.collectionView)
}
lazy var collectionView:UICollectionView = {
var cv = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.flowLayout)
cv.delegate = self
cv.dataSource = self
cv.bounces = true
cv.alwaysBounceVertical = true
cv.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
cv.registerClass(CustomCell.self, forCellWithReuseIdentifier: "cell")
cv.backgroundColor = UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1.0)
return …Run Code Online (Sandbox Code Playgroud) 我开始使用app测试Core Data和iCloud(使用Magical Records).在配置Provisioning Profiles和权利很多麻烦后,应用程序最终运行.一段时间后,应用程序崩溃并抛出此消息::
2012-12-31 03:42:07.079 iCloudTest[252:1103] -[PFUbiquitySafeSaveFile waitForFileToUpload:](268): CoreData: Ubiquity: <PFUbiquityPeerReceipt: 0x1cd5a420>(0)
permanentLocation: <PFUbiquityLocation: 0x1cd57b30>: /private/var/mobile/Library/Mobile Documents/MA5BADG5AW~com~gazapps~iCloudTest/mobile.4088E03C-763E-5A81-BB1B-64CABAFA73E3/com.gazapps.iCloudTest/v8GumdiUYmkE0aO9iGtPTPHX07qqWk7kRytsQwHKjwU=/receipt.0.cdt
safeLocation: <PFUbiquityLocation: 0x1cd57a80>: /private/var/mobile/Library/Mobile Documents/MA5BADG5AW~com~gazapps~iCloudTest/mobile.4088E03C-763E-5A81-BB1B-64CABAFA73E3/com.gazapps.iCloudTest/v8GumdiUYmkE0aO9iGtPTPHX07qqWk7kRytsQwHKjwU=/mobile.4088E03C-763E-5A81-BB1B-64CABAFA73E3.0.cdt
currentLocation: <PFUbiquityLocation: 0x1cd57a80>: /private/var/mobile/Library/Mobile Documents/MA5BADG5AW~com~gazapps~iCloudTest/mobile.4088E03C-763E-5A81-BB1B-64CABAFA73E3/com.gazapps.iCloudTest/v8GumdiUYmkE0aO9iGtPTPHX07qqWk7kRytsQwHKjwU=/mobile.4088E03C-763E-5A81-BB1B-64CABAFA73E3.0.cdt
kv: (null)
Safe save failed for file, error: Error Domain=NSCocoaErrorDomain Code=512 "The file upload timed out." UserInfo=0x1cd5b7d0 {NSLocalizedDescription=The file upload timed out.}
2012-12-31 03:42:07.083 iCloudTest[252:1103] +[MagicalRecord(ErrorHandling) defaultErrorHandler:](0xe5ac0) Error: The file upload timed out.
2012-12-31 03:42:07.085 iCloudTest[252:1103] +[MagicalRecord(ErrorHandling) defaultErrorHandler:](0xe5ac0) Error Message: The file upload timed out.
2012-12-31 …Run Code Online (Sandbox Code Playgroud) 是否可以使用不同的数据模型创建两个不同的领域?
例如:defaultRealm将客户端类用作模型,myRealm将使用products类作为模型
我正在尝试创建一个从底部进入屏幕的视图的动画。但第一次它只出现在屏幕上,没有任何动画,然后它就开始正常工作。
这是代码:
struct ContentView: View {
@State private var showView = false
var body: some View {
ZStack(alignment: .bottom){
VStack{
Button("TAP HERE") {
withAnimation(.spring()) {
showView.toggle()
}
}
Spacer()
}
if showView {
RoundedRectangle(cornerRadius: 30)
.frame(height: UIScreen.main.bounds.height * 0.5)
.transition(.move(edge: .bottom))
}
}
.edgesIgnoringSafeArea(.bottom)
}
Run Code Online (Sandbox Code Playgroud)
}
这是行为:
我做错了什么?
我正在使用 Xcode 14 beta 5 和 Swift 5
我创建了一个 swift 类来测试字典。所以,我写了下面的代码:
import Foundation
class MyClass {
var myFirstDictionary:[String :String]
var myThirdDictionary:[String :String]?
init(){
var mySecondDictionary:[String :String] = [String :String]()
mySecondDictionary["animal"] = "Monkey"
mySecondDictionary.updateValue("something", forKey: "SomeKey")
self.myFirstDictionary = [String :String]()
addOneThingToSecondDictionary()
addAnotherThingToSecondDictionary()
self.myThirdDictionary! = [String :String]()
addOneThingToThirdDictionary()
addAnotherThingToThirdDictionary()
}
func addOneThingToSecondDictionary(){
self.myFirstDictionary["animal"] = "Monkey"
}
func addAnotherThingToSecondDictionary(){
self.myFirstDictionary.updateValue("Superman", forKey: "hero")
}
func addOneThingToThirdDictionary(){
self.myThirdDictionary["animal"]! = "Monkey"
}
func addAnotherThingToThirdDictionary(){
self.myThirdDictionary!.updateValue("Superman", forKey: "hero")
}
}
Run Code Online (Sandbox Code Playgroud)
所以,我收到了 3 个关于“myThirdDictionary”的错误:
我正在尝试使用 AutoLayout 以编程方式创建 UICollectionView,但我遇到了一些问题。
第一次测试:
在我的第一次尝试中,我创建了一个 UICollectionView 作为 Lazy var 并将其添加到 viewDidLoad 中,如下所示:
lazy var collection: UICollectionView = {
let cv = UICollectionView()
cv.translatesAutoresizingMaskIntoConstraints = false
cv.setCollectionViewLayout(self.flowLayout, animated: true)
cv.dataSource = self
cv.delegate = self
cv.registerClass(MyViewCell.self, forCellWithReuseIdentifier: "cell")
return cv
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.collection)
}
Run Code Online (Sandbox Code Playgroud)
这个方法把我带到了这个错误:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“UICollectionView 必须使用非零布局参数进行初始化”
第二次测试:
所以我不得不使用 frame/collectionViewLayout 初始值设定项,我的第二次尝试看起来像这样:
lazy var collection: UICollectionView = {
let cv = UICollectionView(frame: UIScreen.mainScreen().bounds, collectionViewLayout: self.flowLayout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.setCollectionViewLayout(self.flowLayout, animated: true)
cv.dataSource = self
cv.delegate = self …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 Xcode Playground 上运行这个异步函数:
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
enum NetworkingError: Error {
case invalidServerResponse
case invalidCharacterSet
}
func getJson() async throws -> String {
let url = URL(string:"https://jsonplaceholder.typicode.com/todos/1")!
let (data, response) = try await URLSession.shared.data(from: url)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw NetworkingError.invalidServerResponse
}
guard let result = String(data: data, encoding: .utf8) else {
throw NetworkingError.invalidCharacterSet
}
return result
}
let result = try! await getJson()
print(result)
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息:
error: ForecastPlayground.playground:27:25: …Run Code Online (Sandbox Code Playgroud) 我尝试了这个:
let contact = CNMutableContact()
contact.namePrefix = data["firstName"] as! String
contact.nameSuffix = data["lastName"] as! String
contact.organizationName = data["company"] as! String
contact.jobTitle = data["jobTitle"] as! String
let address = CNMutablePostalAddress()
address.street = data["street"] as! String
address.city = data["city"] as! String
address.state = data["state"] as! String
address.postalCode = data["zipcode"] as! String
address.country = data["country"] as! String
contact.postalAddresses = [address]
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
Cannot convert value of type 'CNMutablePostalAddress' to expected element type 'CNLabeledValue<CNPostalAddress>'
Run Code Online (Sandbox Code Playgroud)
所以,我尝试了这个:
let contact = CNMutableContact()
contact.namePrefix = data["firstName"] as! String
contact.nameSuffix …Run Code Online (Sandbox Code Playgroud) swift ×8
ios ×6
core-data ×2
animation ×1
arrays ×1
async-await ×1
autolayout ×1
cncontact ×1
collections ×1
icloud ×1
ios6 ×1
realm ×1
swift5 ×1
swiftui ×1
uiimageview ×1
uitableview ×1
xcode ×1
xcode13 ×1
xcode14 ×1