制作購物車應用程式并遇到問題。我有一個登錄頁面,如果登錄,它將存盤在核心資料中并登錄,但我想讓用戶名出現在另一個視圖控制器 LoginVC 的表視圖中:
import UIKit
import CoreData
class LoginVC: UIViewController {
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view
fetchData()
}
@IBAction func login(_ sender: Any) {
for acc in userList {
if username.text == acc.username && password.text == acc.password {
currentUser = username.text!
try! context.save()
performSegue(withIdentifier: "DisplayShop1", sender: nil)
}
/*else if username.text == "" || password.text == "" || username.text != acc.username || password.text != acc.username {
let alert = UIAlertController(title: "Alert", message: "Please enter the right credentials", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}*/
}
}
func fetchData(){
userList = try! context.fetch(User.fetchRequest())
}
}
ListingShopVC
import UIKit
import CoreData
class ListingShopVC: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var usernameloggedin: UILabel!
@IBOutlet weak var creditsdisplay: UILabel!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var myUser:[User] = []
var mySecond:[Product] = []
var mySecondF:[Product] = []
var id:String = ""
var name:String = ""
var price:Double = 0.0
var image:String = ""
var details:String = ""
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
fetch()
tableView.delegate = self
tableView.dataSource = self
extracted()
usernameloggedin.text = "Welcome \(userList)"
creditsdisplay.text = "You have \(userList)"
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return mySecond.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "hello", for: indexPath) as! TableCellData
// Configure the cell...
cell.shopTitle.text = mySecond[indexPath.row].name
cell.shopPrice.text = "$" String(mySecond[indexPath.row].price) "0"
cell.shopDesc.text = mySecond[indexPath.row].description
if let imageURL = URL(string: mySecond[indexPath.row].image) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
cell.shopImageView.image = image
}
}
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
id = mySecond[indexPath.row].id
name = mySecond[indexPath.row].name
price = mySecond[indexPath.row].price
image = mySecond[indexPath.row].image
//print("At table \(image)")
details = mySecond[indexPath.row].description
performSegue(withIdentifier: "toDetails", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender:Any?){
if segue.identifier == "toDetails"{
let vc = segue.destination as! ProductDetail
vc.productID = id
vc.productName = name
vc.productPrice = price
vc.productPicture = image
vc.productDetails = details
print(vc.productDetails)
}
}
func extracted(){
guard let url = URL(string: "http://rajeshrmohan.com/sport.json")
else {return}
let task = URLSession.shared.dataTask(with: url){
(data,response,error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
do {
let decoder = JSONDecoder()
let model:[Product] = try decoder.decode([Product].self, from: dataResponse)
//print(model)
for i in 0..<model.count{
self.mySecond.append(model[i])
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
@IBAction func logOut(_ sender: Any) {
}
func fetch(){
userList = try! context.fetch(User.fetchRequest())
tableView.reloadData()
}
}
頂部https://i.stack.imgur.com/9RahD.jpg
我只是想讓它出現在頂部,而且我的登錄頁面和代碼似乎無法正常作業如果我將 if 設為空,那么如果有任何可能的建議將不勝感激
uj5u.com熱心網友回復:
據我了解,您無法在頁面之間傳遞資料。將此添加到您從中獲得 userList 的頁面。
@IBAction func okAction(_ sender: Any) {
let controller = storyboard?.instantiateViewController(withIdentifier: "DisplayShop1") as! ListingShopVC
controller.userList = userList
controller.modalPresentationStyle = .fullScreen
present(controller, animated: true, completion: nil)
}
如果您將這個添加到您想稍后傳輸 userList 的頁面中,您可以呼叫 userList。
var userList: String = ""
uj5u.com熱心網友回復:
你幾乎擁有它。您不是將用戶名傳遞到字串中,而是傳遞整個 Core Data 物件串列,這些物件被格式化為字串,但不是您想要的方式。您應該獲取用戶的用戶名,然后將其傳遞到字串中:
let username = userList.first?.username ?? ""
usernameloggedin.text = "Welcome \(username)"
creditsdisplay.text = "You have \(username)"
也就是說,這里有一些評論可以使這項作業更加可靠。
- 我會將這部分代碼移至您的函式以從資料庫加載。這樣,如果您從資料庫重新加載資料,它將獲得正確的用戶,并且名稱將被適當更新。
- 您應該選擇一名正在購物的用戶,并且只選擇一名用戶。目前您正在獲取用戶串列并保留用戶串列。也沒有排序來確定使用哪個用戶,因此它可能會改變中間商店。為了解決這個問題,我建議您創建一個新屬性來存盤型別為 的當前用戶
User,而不是[User],并且只從資料庫加載一個用戶。獲取請求將回傳一個陣列,因此您只需要獲取并保留第一個。此外,為了使這更加可靠,您可以考慮讓您的第一個視圖檢查是否有用戶登錄,從資料庫中獲取該用戶(您已經在這樣做),并使用依賴注入將該用戶傳遞到商店視圖. 有很多關于如何處理這個問題的教程,但基本上你可以在prepareForSegue呼叫中獲得對第二個視圖的參考,并將第二個視圖上的用戶屬性設定為所需的用戶,從而“注入你的依賴項”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/369971.html
上一篇:使UIButton影像適合按鈕
