【发布时间】:2022-01-03 11:44:46
【问题描述】:
制作购物车应用程序并遇到问题。我有一个登录页面,如果登录,它将存储在核心数据和登录中,但我想让用户名出现在另一个视图控制器的表视图上 登录VC:
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 空所以如果有任何可能的建议将不胜感激
【问题讨论】:
-
您在错误的地方将用户名设置为相应的文本字段。
标签: arrays swift xcode shopping-cart shopping