- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 detailviewcontroller 文件,其中有一个 ImageView 、一个文本字段、一个 TextView 和一个日期选择器。 ImageView 图像让我从第一个 Controller 。当我填写文本字段、 TextView 、选择日期等剩余数据时,然后当我单击导航栏中的保存按钮时,数据应保存在 nsuserdefault 中并传递到另一个 Controller 的 TableView 。当我再次启动应用程序并再次填写详细信息时,该数据和以前的数据也应该在那里。不知道该怎么做
我的 detailviewcontroller 文件:
class DetailsViewController: UIViewController{
var picker : UIDatePicker = UIDatePicker()
@IBOutlet weak var selectedDate: UIButton!
@IBOutlet weak var detailsVCImage: UIImageView!
@IBOutlet weak var geoAddressLabel: UILabel!
@IBOutlet weak var titleTF: UITextField!
@IBOutlet weak var notesTextView: CustomTextView!
var mapView:GMSMapView!
var transferedImage:UIImage!
var arrayList = [[String:Any]]()
var obj = [String:Any]()
override func viewDidLoad() {
super.viewDidLoad()
notesTextView.text = "Please enter Notes...."
notesTextView.textColor = .lightGray
detailsVCImage.image = transferedImage
hideKeyboardWhenTapped()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
dismiss(animated: true)
}
@IBAction func datePickerTapped(_ sender: Any) {
picker.datePickerMode = UIDatePickerMode.dateAndTime
picker.addTarget(self, action: #selector(dueDateChanged(sender:)), for: UIControlEvents.valueChanged)
// self.picker = UIDatePicker(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 85))
let pickerSize : CGSize = picker.sizeThatFits(CGSize.zero)
picker.frame = CGRect(x:0.0, y:442, width:pickerSize.width, height:85)
//width: 288
self.view.addSubview(picker)
}
@objc func dueDateChanged(sender:UIDatePicker){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
selectedDate.setTitle(dateFormatter.string(from: sender.date), for: .normal)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
picker.removeFromSuperview()
}
@IBAction func saveDataTaopped(_ sender: Any) {
obj["title"] = titleTF.text
obj["notes"] = notesTextView.text
obj["image"] = transferedImage
obj["date"] = selectedDate
arrayList.append(obj)
}
func reverseGeocodeCoordinate(_ coordinate: CLLocationCoordinate2D) {
let geocoder = GMSGeocoder()
geocoder.reverseGeocodeCoordinate(coordinate) { response, error in
// self.geoAddressLabel.unlock()
guard let address = response?.firstResult(), let lines = address.lines else {
return
}
self.geoAddressLabel.text = lines.joined(separator: "\n")
let labelHeight = self.geoAddressLabel.intrinsicContentSize.height
//// self.mapView.padding = UIEdgeInsets(top: self.view.safeAreaInsets.top, left: 0,
// bottom: labelHeight, right: 0)
//
// UIView.animate(withDuration: 0.25) {
// self.pinImageVerticalConstraint.constant = ((labelHeight - self.view.safeAreaInsets.top) * 0.5)
// self.view.layoutIfNeeded()
// }
}
}
@IBAction func getLocationAddress(_ sender: Any) {
// reverseGeocodeCoordinate(target)
}
}
extension DetailsViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func hideKeyboardWhenTapped () {
let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(DetailsViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
extension DetailsViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
// reverseGeocodeCoordinate(position.target)
}
// func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
// geoAddressLabel.lock()
//
// if (gesture) {
// mapCenterPinImage.fadeIn(0.25)
// mapView.selectedMarker = nil
// }
// }
}
我的 listtableviewcontroller 文件:
class ListTableViewController: UITableViewController {
@IBOutlet weak var listImage: UIImageView!
@IBOutlet weak var listTitle: UILabel!
@IBOutlet weak var listNotes: UITextView!
@IBOutlet weak var listDate: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
最佳答案
使用核心数据
ViewController.swift
import UIKit
import CoreData
class ViewController: UIViewController {
@IBOutlet weak var imgVw: UIImageView!
@IBOutlet weak var titleTxt: UITextField!
@IBOutlet weak var descTxt: UITextView!
@IBOutlet weak var dateTxt: UIDatePicker!
var idd: UInt64 = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.clearContent()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(
dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
@IBAction func SaveClk(_ sender: Any) {
idd = Date().ticks
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Product", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)
let imageData: NSData = (imgVw.image)!.pngData()! as NSData
newUser.setValue(dateTxt.date, forKey: "pDate")
newUser.setValue(descTxt.text, forKey: "pDesc")
newUser.setValue(titleTxt.text, forKey: "pTitle")
newUser.setValue(String(idd), forKey: "pid")
newUser.setValue(imageData, forKey: "pimg")
do {
try context.save()
let alertController = UIAlertController(title: "Alert", message: "Added!", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
// Code in this block will trigger when OK button tapped.
self.clearContent()
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "DetailsViewControllerID") as! DetailsViewController
self.navigationController?.pushViewController(nextViewController, animated: true)
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion:nil)
} catch {
print("Failed saving")
}
}
func clearContent(){
self.descTxt.text = ""
self.titleTxt.text = ""
self.imgVw.image = UIImage(named: "profImage")
}
@IBAction func CamClk(_ sender: Any) {
CameraHandler.shared.showActionSheet(vc: self)
CameraHandler.shared.imagePickedBlock = { (image) in
self.imgVw.image = image
}
}
@IBAction func NxtVw(_ sender: Any) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "DetailsViewControllerID") as! DetailsViewController
self.navigationController?.pushViewController(nextViewController, animated: true)
}
}
extension Date {
var ticks: UInt64 {
return UInt64((self.timeIntervalSince1970 + 62_135_596_800) * 10_000_000)
}
}
DetailsViewController.swift
import UIKit
import CoreData
class DetailsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var result: [NSManagedObject] = []
@IBOutlet weak var tblList: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.fetchData()
self.tblList.reloadData()
// Do any additional setup after loading the view.
}
func fetchData() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Product")
do {
result = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
// MARk: - tableViewDelegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return result.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let record = result[indexPath.row]
let cell:listData = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath as IndexPath) as! listData
cell.lblTitle.text = record.value(forKeyPath: "pTitle") as? String
let formatter = DateFormatter()
formatter.dateFormat = "dd-MMM-yyyy"
let myString = formatter.string(from: record.value(forKeyPath: "pDate") as! Date)
cell.lblDate.text = myString
cell.lblDesc.text = record.value(forKeyPath: "pDesc") as? String
cell.imgPro.image = UIImage(data: (record.value(forKey:"pimg") as! Data), scale: 1.0)
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let record = result[indexPath.row]
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Product")
request.predicate = NSPredicate(format: "pid = %@", (record.value(forKeyPath: "pid") as? String)!)
request.returnsObjectsAsFaults = false
do {
let objects = try context.fetch(request)
for object in objects {
context.delete(object as! NSManagedObject)
}
try context.save()
} catch _ {
// error handling
}
fetchData()
tblList.reloadData()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
class listData: UITableViewCell {
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblDate: UILabel!
@IBOutlet weak var lblDesc: UILabel!
@IBOutlet weak var imgPro: UIImageView!
}
CameraHandler.swift
import UIKit
import Foundation
class CameraHandler: NSObject {
static let shared = CameraHandler()
fileprivate var currentVC: UIViewController!
//MARK: Internal Properties
var imagePickedBlock: ((UIImage) -> Void)?
func camera()
{
if UIImagePickerController.isSourceTypeAvailable(.camera){
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.allowsEditing = true
myPickerController.sourceType = .camera
currentVC.present(myPickerController, animated: true, completion: nil)
}
}
func photoLibrary()
{
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.allowsEditing = true
myPickerController.sourceType = .photoLibrary
currentVC.present(myPickerController, animated: true, completion: nil)
}
}
func showActionSheet(vc: UIViewController) {
currentVC = vc
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (alert:UIAlertAction!) -> Void in
self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { (alert:UIAlertAction!) -> Void in
self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
vc.present(actionSheet, animated: true, completion: nil)
}
}
extension CameraHandler: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
currentVC.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.imagePickedBlock?(image)
}else{
print("Something went wrong")
}
currentVC.dismiss(animated: true, completion: nil)
}
}
AppDelegate.swift
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreData_Sample")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
输出
关于ios - 想将数据保存在 nsuserdefault 中并将其传输到另一个 Controller 的 TableView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55790400/
SELECT *, `o_cheque_request.member_id`, `o_cheque_request.wallet_id` FROM `o_cheque_request`, `o_mem
根据某一条件从数据库表中查询 『有』与『没有』,只有两种状态,那为什么在写SQL的时候,还要**SELECT count(*)**呢? 无论是刚入道的程序员新星,还是精湛沙场多年的程序员老白,都是一如
我试图找出一个文件是否存在,如果存在,验证css样式是否已经存在,如果不存在,将它们写在文件末尾... 我已经完成了这一切,但分 3 个步骤: 该文件是否存在? FileInfo fi= new Fi
我们正在开发即时消息传递应用程序,并且需要在用户的化身上用绿点显示用户 friend 的“状态”。 “状态”远远超出了“my_app_is_opened_and_on_focus”,这意味着(我猜可能
模式 Movie(title, year, director, budget, earnings) Actor(stagename, realname, birthyear) ActedIn(stag
我有一个正在尝试创建的 MySQL 触发器,但无法获得正确的语法。 触发器应该遍历一组关键字并将其与插入数据库的新帖子的标题进行匹配。如果找到匹配项,它应该将新帖子分配给该存储桶并更新存储桶的关键字集
我有 3 个表......用户、更新和碰撞。 我想向发出 api 请求的用户返回最新订单的 feed 更新,并提供显示 feed 中每个状态所需的所有数据。我还需要包括更新是否已被发出 api 请求的
我正在尝试呈现一个带有 UIView 的 UIViewController。 以下是我在 viewDidLoad 方法中尝试的代码。 //create the view controller UIVi
我正在努力弄清楚如何在不对 mysql 进行两次调用的情况下从一个表中检查两件事。 我有一个 Members 表。我想测试MemberID 列中是否存在某个值,以及PhoneNumber 列中是否存在
以下代码给出了一个没有 Do Compile 错误的循环: Loop Sheets("Snap").Rows(1).AutoFilter Field:=5, Criteria1:=List
是否可以通过检查“dig”的输出来检查域名的存在? 在绑定(bind)源中,我发现了这些常量: 0 DNS_R_NOEROR 1 DNS_R_FORMERR 2 DNS_R_SERVFAIL 3 DN
Controller 有问题 我在 Windows 上使用服务器,一切正常,但在互联网上我试图访问页面 social_apartament/beauty_life/并且找不到该页面,代码错误 404这
/** This is struct S. */ struct S(T) { static if(isFloatingPoint!T) { /// This version works
JVM 类型删除如何帮助 Clojure?没有它,Clojure 还能存在吗?如果 JVM 有具体化的类型会发生什么?也就是说,Clojure 将如何改变? 最佳答案 Clojure 根本不会有太大变
许多论文等提到对“system()”的调用是不安全且不可移植的。我不反对他们的论点。 不过,我注意到许多 Unix 实用程序都有一个等效的 C 库。如果没有,源可用于各种这些工具。 虽然许多论文和此类
在我的 Node js 应用程序中,我有一个用户登录 api。上面我在服务器端代码中创建了一个名为 customerid 的变量。现在,当用户身份验证成功时。我将他的 userid 值存储在我的 cu
我有一个工作资源管理器组,由 Ubuntu 14.04 虚拟机、网络接口(interface)、公共(public) IP 地址和存储帐户组成。我已经从这组资源中创建了一个模板。 当我尝试部署这组资源
我有一个函数createminor4(arr,锦标赛)它基本上将arr分成4组,每组8人,然后将它们一次交换到tourney 1组。从那里它插入四个{},其中有 4 个带有空数组的键。 我已经在 Ch
我有一个图表,其中有两个图例。我需要更改其中一个图例的点的大小。 我需要更改图例中“市场类型”的项目符号大小。我使用示例 here但不适用于我的图表。 我的代码如下: k <- ggplot(subs
我有 fiddle here展示我正在尝试做的事情。 我有一个动态生成的表,因此列可以按用户选择的任何顺序显示。因此,我尝试获取两个特定 header 的索引,以便可以将 CSS 类添加到这两列以供稍
我是一名优秀的程序员,十分优秀!