我如何使用文本字段警报操作来更新单独的UIViewController上的标签?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我如何使用文本字段警报操作来更新单独的UIViewController上的标签?相关的知识,希望对你有一定的参考价值。

我目前正在为一个班级开发一个简单的记分板应用程序。我为不同的事物设置了多个视图控制器。 ScoreboardViewControllerPlayerListTableViewControllerPlayerInfoViewController

ScoreboardViewController是我的记分板应用程序,在这里我可以使用不同的按钮来添加或减去与触地得分,射门得分或加分值得多少有关的某个值。

PlayerListTableViewController上,我在表格视图中有一个虚构的玩家列表,可以单击以显示PlayerInfoViewController

PlayerInfoViewController是显示他们的姓名,球员号码和得分的得分的下一页。

在第一个视图控制器上,当我单击“添加触摸向下”按钮时,将弹出一个警报,允许我输入得分的玩家的姓名或号码。

我如何使用此警报来更新每个球员选项卡中的标签,以反映他们得分的达阵数?我也只希望玩家的名字或玩家的号码是有效的输入。根据输入的姓名或号码,我希望他们的标签每次输入某个球员的姓名时都增加一个。

例如,如果我输入“ Player 1”或仅输入“ 01”,我只希望特定玩家的达阵数使该游戏增加1。此过程可以对每个玩家重复多次。

App Delegate Array

        var window: UIWindow?
    var players: [Dictionary<String, String>] = []


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool 
        // Override point for customization after application launch.

        //An array of players with each player being a dictionary with playerFirstName, playerLastName, playerNumber, and playerTouchdowns

        players.append(["playerFirstName": "Kaden", "playerLastName": "Hampton", "playerNumber": "02", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Jack", "playerLastName": "Mckineey", "playerNumber": "03", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Garret", "playerLastName": "Hampton", "playerNumber": "04", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Cameron", "playerLastName": "Wilkins", "playerNumber": "05", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Kayshawn", "playerLastName": "Woods", "playerNumber": "06", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Jessie", "playerLastName": "Padgett", "playerNumber": "07", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Cameron", "playerLastName": "Richardson", "playerNumber": "07", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Kiylan", "playerLastName": "Miller", "playerNumber": "08", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Stoney", "playerLastName": "Hicks", "playerNumber": "09", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Damian", "playerLastName": "Boykins", "playerNumber": "10", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Amarion", "playerLastName": "Johnson", "playerNumber": "11", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Darian", "playerLastName": "Huber", "playerNumber": "12", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Jake", "playerLastName": "Cochran", "playerNumber": "12", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Bailey", "playerLastName": "McGinnis", "playerNumber": "14", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "E'marion", "playerLastName": "Mckinney", "playerNumber": "15", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Jamarion", "playerLastName": "Mills", "playerNumber": "16", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Chandler", "playerLastName": "Anderson", "playerNumber": "17",
                "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Kameron", "playerLastName": "Mills", "playerNumber": "18", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Elijah", "playerLastName": "Guest", "playerNumber": "20", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Darin", "playerLastName": "Johnson", "playerNumber": "21", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Mason", "playerLastName": "Monteith", "playerNumber": "23", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Taivon", "playerLastName": "Derisma", "playerNumber": "24", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Dylan", "playerLastName": "Lanser", "Richardson": "30", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Chris", "playerLastName": "Lanser", "Lanser": "32", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Caleb", "playerLastName": "Lanser", "playerNumber": "33", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Anthony", "playerLastName": "Smith", "playerNumber": "36", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Brenon", "playerLastName": "Austin", "playerNumber": "40", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Austin", "playerLastName": "Charles", "playerNumber": "42", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Kahseem", "playerLastName": "Corpening", "playerNumber": "44", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Nick", "playerLastName": "Robbins", "playerNumber": "48", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Tragen", "playerLastName": "Moore", "playerNumber": "50", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Bryson", "playerLastName": "Green", "playerNumber": "52", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Mackey", "playerLastName": "Flynn", "playerNumber": "55", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Cody", "playerLastName": "Wells", "playerNumber": "56", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Luke", "playerLastName": "McGinnis", "playerNumber": "57", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Noah", "playerLastName": "Palmeri", "playerNumber": "58", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Mitchell", "playerLastName": "McCraw", "playerNumber": "60", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Carson", "playerLastName": "Jones", "playerNumber": "61", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Robert", "playerLastName": "Ward", "playerNumber": "61", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Kaleb", "playerLastName": "Metz", "playerNumber": "66", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Damian", "playerLastName": "Turpin", "playerNumber": "68", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Carson", "playerLastName": "Jones", "playerNumber": "70", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Chris", "playerLastName": "Greene", "playerNumber": "71", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Aeneas", "playerLastName": "Harris", "playerNumber": "73", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Reagan", "playerLastName": "McCraine", "playerNumber": "74", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Chris", "playerLastName": "Moore", "playerNumber": "78", "playerTouchDowns": "0"])
        players.append(["playerFirstName": "Samuel", "playerLastName": "Perry", "playerNumber": "81", "playerTouchDowns": "0"])


        return true
    

记分板代码

var score: Int = 0
let touchDownPoints = 6
let fieldGoalPoints = 3
let extraPointPoints = 1

// Variables
var NumberOfTouchdowns = 0
var NumberOfFieldGoals = 0
var NumberOfExtraPoints = 0




 let appDelegate = UIApplication.shared.delegate as! AppDelegate

override func viewDidAppear(_ animated: Bool) 

override func viewDidLoad() 
    super.viewDidLoad()
    // Do any additional setup after loading the view.


// Outlets for each button and label.

@IBOutlet weak var scoreLabel: UILabel!

@IBOutlet weak var AddTouchDown: UIButton!

@IBOutlet weak var AddFieldGoal: UIButton!

@IBOutlet weak var AddExtraPoint: UIButton!

@IBOutlet weak var TouchDownLabel: UILabel!

@IBOutlet weak var FieldGoalLabel: UILabel!

@IBOutlet weak var ExtraPointLabel: UILabel!

@IBOutlet weak var SubtractTouchDown: UIButton!

@IBOutlet weak var SubtractFieldGoal: UIButton!

@IBOutlet weak var SubtractExtraPoint: UIButton!

//  @IBOutlet weak var ConfirmButton: UIButton!

// @IBOutlet weak var DenyButton: UIButton!

// Actions for each button.


@IBAction func AddTouchDown(_ sender: UIButton) 
    print("A touchdown was added")
    self.scoreLabel.text = " \(score + touchDownPoints) "
        score += touchDownPoints
    self.TouchDownLabel.text = " \(NumberOfTouchdowns + 1)"
        NumberOfTouchdowns += 1
    createAddTouchDownAlert(title: "Player Number", message: "Who 
scored the touchdown?")



@IBAction func AddFieldGoal(_ sender: UIButton) 
    print("A field goal was added")
    self.scoreLabel.text = " \(score + fieldGoalPoints)"
        score += fieldGoalPoints
    self.FieldGoalLabel.text = " \(NumberOfFieldGoals + 1)"
        NumberOfFieldGoals += 1


@IBAction func AddExtraPoint(_ sender: UIButton) 
    print("An extra point was added")
    self.scoreLabel.text = " \(score + extraPointPoints)"
        score += extraPointPoints
    self.ExtraPointLabel.text = " \(NumberOfExtraPoints + 1)"
        NumberOfExtraPoints += 1


@IBAction func SubtractTouchDown(_ sender: UIButton) 
    print("A touchdown was subtracted")
    self.scoreLabel.text = " \(score - touchDownPoints)"
        score -= touchDownPoints
    self.TouchDownLabel.text = " \(NumberOfTouchdowns - 1)"
        NumberOfTouchdowns -= 1


@IBAction func SubtractFieldGoal(_ sender: UIButton) 
    print("A field goal was subtracted")
    self.scoreLabel.text = " \(score - fieldGoalPoints)"
        score -= fieldGoalPoints
    self.FieldGoalLabel.text = " \(NumberOfFieldGoals - 1)"
        NumberOfFieldGoals -= 1


@IBAction func SubtractExtraPoint(_ sender: UIButton) 
    print("An extra point was subtracted")
    self.scoreLabel.text = " \(score - extraPointPoints)"
        score -= extraPointPoints
    self.ExtraPointLabel.text = " \(NumberOfExtraPoints - 1)"
        NumberOfExtraPoints -= 1


@IBAction func ResetButtonPressed(_ sender: UIButton) 
    let alert = UIAlertController(title: "Notice", message: "You are 
about to reset the scoreboard. Do you wish to continue?", 
preferredStyle: UIAlertController.Style.alert)

    alert.addAction(UIAlertAction(title: "Continue", style: 
UIAlertAction.Style.default, handler:  action in
        self.ResetButton()
    ))
    alert.addAction(UIAlertAction(title: "Cancel", style: 
UIAlertAction.Style.cancel, handler: nil))

    self.present(alert, animated: true, completion: nil)

func ResetButton() 
print("Score has been reset")
    self.scoreLabel.text = " \(score - score)"
            score -= score
    self.TouchDownLabel.text = " \(NumberOfTouchdowns - 
NumberOfTouchdowns)"
        NumberOfTouchdowns -= NumberOfTouchdowns

    self.FieldGoalLabel.text = " \(NumberOfFieldGoals - 
NumberOfFieldGoals)"
            NumberOfFieldGoals -= NumberOfFieldGoals

    self.ExtraPointLabel.text = " \(NumberOfExtraPoints - 
NumberOfExtraPoints)"
            NumberOfExtraPoints -= NumberOfExtraPoints


// Add Touchdown Alert
func createAddTouchDownAlert(title: String, message: String) 
    let alert = UIAlertController(title: title, message: message, 
preferredStyle: UIAlertController.Style.alert)

    alert.addTextField  (textField) in
        textField.text = "0"
    

    alert.addAction(UIAlertAction(title: "OK", style: 
UIAlertAction.Style.default, handler: nil))

    self.present(alert, animated: true, completion: nil)




PlayerListTableViewController

import UIKit

class PlayerListTableViewController: UITableViewController 

let appDelegate = UIApplication.shared.delegate as! AppDelegate

var playerSelected = 0

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


// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int 
    // #warning Incomplete implementation, return the number of 
sections
    return 1


override func tableView(_ tableView: UITableView, numberOfRowsInSection 
section: Int) -> Int 
    // #warning Incomplete implementation, return the number of rows
    return appDelegate.players.count



override func tableView(_ tableView: UITableView, cellForRowAt 
indexPath: IndexPath) -> UITableViewCell 
    let cell = tableView.dequeueReusableCell(withIdentifier: 
"PlayerList Cell", for: indexPath)

    let firstName = appDelegate.players[indexPath.row] . 
["playerFirstName"]

    let lastName = appDelegate.players[indexPath.row]["playerLastName"]

    cell.textLabel?.text = firstName! + " " + lastName!

    // Configure the cell...

    return cell


override func tableView(_ tableView: UITableView, didSelectRowAt 
indexPath: IndexPath) 
    playerSelected = indexPath.row
    performSegue(withIdentifier: "Show Info", sender: nil)


override func prepare(for segue: UIStoryboardSegue, sender: Any?) 
    if (segue.identifier == "Show Info") 
        let playerInfoViewController: PlayerInfoViewController = 
segue.destination as! PlayerInfoViewController
        playerInfoViewController.playerIndex = playerSelected
    

PlayerInfoViewController

import UIKit

class PlayerInfoViewController: UIViewController 

var playerIndex = 0
let appDelegate = UIApplication.shared.delegate as! AppDelegate

var touchDownsScored = String()


@IBOutlet weak var FirstName: UILabel!

@IBOutlet weak var LastName: UILabel!

@IBOutlet weak var PlayerNumber: UILabel!

@IBOutlet weak var TouchdownsScored: UILabel!

override func viewDidLoad() 
    super.viewDidLoad()

    FirstName.text = appDelegate.players[playerIndex] . 
["playerFirstName"]
    LastName.text = appDelegate.players[playerIndex]["playerLastName"]
    PlayerNumber.text = appDelegate.players[playerIndex] . 
["playerNumber"]
    TouchdownsScored.text = appDelegate.players[playerIndex] . 
["playerTouchDowns"]

[如果有人知道该怎么做,并且可以引导我朝正确的方向,请向我提供任何建议或知识。

答案

对于初学者,我将使用播放器结构来保存详细信息,而不是笨拙的数组,并提供一些辅助方法:

struct Player 
  let firstName: String
  let lastname: String
  let number: Int
  var touchDowns = 0

  func touchDown()
    touchdowns += touchDownValue
  

  func matches(text: String) -> Bool
    //do someting to match the text against the record, maybe...
    return firstname == text || (Int(text) != nil && Int(text) == number)
  


var players = [Player] 
//leaving as an array for now, although Dict or Set may be more efficient

并使用默认的逐级初始化程序,使用播放器详细信息填充数组。

然后,我将完成闭合添加到操作中,以获取文本字段的内容,将其与数组匹配,然后将触地得分添加到该玩家的记录中。然后执行所需的任何UI更新。

let alertController = UIAlertController(title: "Player?", message: "name or number", preferredStyle: .alert)
alertController.addTextField  (textField) in
     textField.text = "0"
 
let action = UIAlertAction(title: "Done", style: .default) [unowned ac] _ in
    let player = alertController.textFields![0]
    let index = self.players.firstIndex(where $0.matches(text))
    self.players[index].touchDown()
    //do any UI updates you need
   
  alertController.addAction(action)
  present(alertController, animated: true)

注意:我尚未编译此文件,因此可能会有轻微的拼写错误/语法错误,但是ti应该适合您从中实现。

以上是关于我如何使用文本字段警报操作来更新单独的UIViewController上的标签?的主要内容,如果未能解决你的问题,请参考以下文章

如何知道哪个uiview用户正在使用

如何将文本字段添加到警报视图? Xcode 4.5 iOS6

如何更改系统警报设置文本动态

使用动态约束对齐文本字段

核心数据:如何从警报中更新 TableView 字段?

如何在警报中访问 Uitextfield 的文本?