以编程方式创建 VC,使用公式中文本字段中的整数并在点击 UIButton 时执行计算

Posted

技术标签:

【中文标题】以编程方式创建 VC,使用公式中文本字段中的整数并在点击 UIButton 时执行计算【英文标题】:programmatically create VC, Use integers from UItext field in formula and perform a calculation when UIButton is tapped 【发布时间】:2020-03-29 01:52:17 【问题描述】:

所有,此代码现在不会抛出错误,但屏幕是空白的。我正在尝试创建一个简单的计算器。用户将数字输入到 3 个单独的 UIText 字段中,按下按钮,UILabel 会给出答案。我知道我还没有标签。我首先构建了一个容器来保存文本字段,但后来我的“CalculateTapped”无法将文本字段视为变量。

问题。 1 为什么我的屏幕现在是黑的? 问题。 2. 为什么我不能让 CalculateTapped 更早地从我的惰性 var "" 视图中读取 UIText 字段?

如果有人有任何意见,我将不胜感激。试图摆脱故事板。

导入 UIKit

class PitchLineVC: UIViewController 



    override func viewDidLoad() 
            super.viewDidLoad()
        let view = UIView()
            ()
            view.backgroundColor = .white
            view.anchor(top: view.topAnchor, left: view.leftAnchor,bottom: view.bottomAnchor, right: view.rightAnchor);
            configureNavigationBar()

    //        looks for keyboard instance
            NotificationCenter.default.addObserver(self, selector: #selector(PitchLineVC.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(PitchLineVC.keyboarWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
        

    //   keeps screen from rotating
    override var shouldAutorotate: Bool 
            return false
      

//  Add text fields for user input to calculate pitch
    private lazy var areaTxt: UITextField! = 
    let area = UITextField()

    area.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: -100).isActive = true
    area.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -300).isActive = true
    area.placeholder = "Bar Area"
    area.textAlignment = .center
    area.borderStyle = UITextField.BorderStyle.line
    area.backgroundColor = UIColor.white
    area.textColor = UIColor.black
    area.keyboardType = UIKeyboardType.decimalPad
//    view.addSubview(area)
        return(area)
    ()
        private lazy var areaTop: UITextField! = 
        let area = UITextField()

        area.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        area.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -200).isActive = true
        area.placeholder = "Top Area of Bar"
        area.textAlignment = .center
        area.borderStyle = UITextField.BorderStyle.line
        area.backgroundColor = UIColor.white
        area.textColor = UIColor.black
        area.keyboardType = UIKeyboardType.decimalPad
//        view.addSubview(area)
            return(area)
    ()

        private lazy var lineLength: UITextField! = 
            let line = UITextField()

            line.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: -100).isActive = true
            line.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -300).isActive = true

//            line.anchor(top: view.bottomAnchor, paddingTop: -80,width: 100, height: 35)
            line.placeholder = "Line Length"
            line.textAlignment = .center
            line.borderStyle = UITextField.BorderStyle.line
            line.backgroundColor = UIColor.white
            line.textColor = UIColor.black
            line.keyboardType = UIKeyboardType.decimalPad
//            view.addSubview(line)
            return (line)
        ()


    @objc func CalculateTapped()
                       print("Button Tapped")
            let AreaTotal = Double(areaTxt.text!)
                let AreaTop = Double(areaTop.text!)
                let Line = Double(lineLength.text!)

                if AreaTotal != nil && AreaTop != nil && Line != nil

                    let LineMove = -(((AreaTotal! / 2) - AreaTop!) / Line!)

                    movepitchline.text = NSString(format: "%.3f", LineMove) as String
                

                   

            func addCalculateButton()
                   let Calculate = UIButton()

                    Calculate.addTarget(self, action: #selector(CalculateTapped), for: .touchUpInside)
                    Calculate.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: -100).isActive = true
                    Calculate.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -400).isActive = true
                    Calculate.anchor(top: view.bottomAnchor, paddingTop: -80,
                                           width: 100, height: 35)
                view.addSubview(Calculate)

                   

    let movepitchline: UILabel = 
        let label = UILabel()
        label.textAlignment = .right
        label.frame = CGRect(x: 10, y: 380, width: 220, height: 35)
        label.text = "Move Pitch:"
        label.font = UIFont.boldSystemFont(ofSize: 23)
        label.textColor = .black
        return label
    ()


//    When keyboard displays the UIView shift up
    @objc func keyboardWillShow(notification: NSNotification) 
        guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else 
           // if keyboard size is not available for some reason, dont do anything
           return
        
      // move the root view up by the distance of keyboard height
      self.view.frame.origin.y = 150 - keyboardSize.height
    

    @objc func keyboarWillHide(notification: NSNotification)
        self.view.frame.origin.y = 0//\\100 + keyboardSize.height
    

//    select outside text box to dismiss selection
    @objc func handleDismiss(notification: NSNotification) 
        dismiss(animated: true, completion: nil)
    

    func configureNavigationBar() 
        navigationController?.navigationBar.barTintColor = .appBlue
        navigationController?.navigationBar.barStyle = .black

        navigationItem.title = "Pass Pitch and Diameters"
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "Home_2x").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleDismiss))

    


【问题讨论】:

修复了它并添加了一些其他功能,例如使用数字键盘关闭键盘。 【参考方案1】:
import UIKit

class PitchLineVC: UIViewController 


    lazy var pitchlogoView: UIImageView = 
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFit
        iv.clipsToBounds = true
        iv.image = #imageLiteral(resourceName: "PITCH LINE")
        return iv
    ()

    lazy var areaTxt: UITextField! = 
        let tf = UITextField()

        tf.placeholder = "Bar Area"
        tf.textAlignment = .center
        tf.borderStyle = UITextField.BorderStyle.line
        tf.backgroundColor = UIColor.white
        tf.textColor = UIColor.black
        tf.keyboardType = UIKeyboardType.decimalPad
            return(tf)
        ()

    lazy var areaTop: UITextField! = 
            let tf = UITextField()

            tf.placeholder = "Top Area of Bar"
            tf.textAlignment = .center
            tf.borderStyle = UITextField.BorderStyle.line
            tf.backgroundColor = UIColor.white
            tf.textColor = UIColor.black
            tf.keyboardType = UIKeyboardType.decimalPad
                return(tf)
        ()

    lazy var lineLength: UITextField! = 
                let tf = UITextField()

                tf.placeholder = "Line Length"
                tf.textAlignment = .center
                tf.borderStyle = UITextField.BorderStyle.line
                tf.backgroundColor = UIColor.white
                tf.textColor = UIColor.black
                tf.keyboardType = UIKeyboardType.decimalPad
                return (tf)
            ()

    lazy var movepitchline1: UILabel = 
               let lb = UILabel()
               lb.textAlignment = .right
               lb.frame = CGRect(x: 10, y: 380, width: 220, height: 35)
               lb.text = "Move Pitch: + is up, - is down"
               lb.textAlignment = .center
               lb.font = UIFont.boldSystemFont(ofSize: 23)
               lb.textColor = .black
               return (lb)
           ()

    lazy var movepitchline: UILabel = 
        let lb = UILabel()
        lb.textAlignment = .right
        lb.frame = CGRect(x: 10, y: 380, width: 220, height: 35)
        lb.text = ""
        lb.textAlignment = .center

        lb.font = UIFont.boldSystemFont(ofSize: 23)
        lb.textColor = .black
        return (lb)
    ()


    let calculateButton: UIButton = 
        let button = UIButton(type: .system)

        button.backgroundColor = UIColor.init(red: 48/255, green: 173/255, blue: 99/255, alpha: 1)
        button.layer.cornerRadius = 25.0
        button.tintColor = UIColor.white
        button.layer.shadowColor = UIColor.darkGray.cgColor
        button.layer.shadowRadius = 6
        button.layer.shadowOpacity = 0.7
        button.layer.shadowOffset = CGSize(width: 0, height: 0)
        button.setTitle("Calculate", for: .normal)
        button.titleLabel?.font = UIFont(name: "Copperplate", size: 22)
        button.addTarget(self, action: #selector(handleCalculate), for: .touchUpInside)
        return button
    ()

    @objc func handleDismiss(notification: NSNotification) 
        dismiss(animated: true, completion: nil)
    

    //sets trigger for keyboard dismiss
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
        view.endEditing(true)
        super.touchesBegan(touches, with: event)
    

//    Mark: Init
    override func viewDidLoad() 
            super.viewDidLoad()

        configureNavigationBar()
        configureViewComponent()

    //        looks for keyboard instance
            NotificationCenter.default.addObserver(self, selector: #selector(PitchLineVC.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(PitchLineVC.keyboarWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
        

    //   keeps screen from rotating
    override var shouldAutorotate: Bool 
            return false
    

//    Mark: Selectors


    @objc func handleCalculate()
    
        print("calculate")
        guard let AreaTotal = Double(areaTxt.text!) else return
        guard let AreaTop = Double(areaTop.text!) else return
        guard let Line = Double(lineLength.text!) else return


        if AreaTotal != 0 && AreaTop != 0 && Line != 0

            let LineMove = -(((AreaTotal / 2) - AreaTop) / Line)
            print(LineMove)
            movepitchline.text = NSString(format: "%.3f", LineMove) as String

         else
            print("Error in fields, please check entry")
        

    

    func configureViewComponent()
        view.backgroundColor = .white

        view.addSubview(pitchlogoView)
        pitchlogoView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 120, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 250, height: 110)

        view.addSubview(areaTxt)
        areaTxt.anchor(top: pitchlogoView.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 15, paddingLeft: 80, paddingBottom: 0, paddingRight: 80, width: 0, height: 30)

        view.addSubview(areaTop)
        areaTop.anchor(top: areaTxt.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 20, paddingLeft: 80, paddingBottom: 0, paddingRight: 80, width: 0, height: 30)

        view.addSubview(lineLength)
        lineLength.anchor(top: areaTop.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 20, paddingLeft: 80, paddingBottom: 0, paddingRight: 80, width: 0, height: 30)

        view.addSubview(calculateButton)
        calculateButton.anchor(top: lineLength.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 30, paddingLeft: 32, paddingBottom: 0, paddingRight: 32, width: 0, height: 50)

        view.addSubview(movepitchline1)
        movepitchline1.anchor(top: calculateButton.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 10, paddingLeft: 32, paddingBottom: 0, paddingRight: 32, width: 0, height: 40)

        view.addSubview(movepitchline)
        movepitchline.anchor(top: movepitchline1.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 10, paddingLeft: 32, paddingBottom: 0, paddingRight: 32, width: 0, height: 40)
        

//    When keyboard displays the UIView shift up
    @objc func keyboardWillShow(notification: NSNotification) 
        guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else 
           // if keyboard size is not available for some reason, dont do anything
           return
        
      // move the root view up by the distance of keyboard height

      self.view.frame.origin.y = 165 - keyboardSize.height
    

    @objc func keyboarWillHide(notification: NSNotification)
        self.view.frame.origin.y = 0
    

//    select outside text box to dismiss selection

    func configureNavigationBar() 
        navigationController?.navigationBar.barTintColor = .appBlue
        navigationController?.navigationBar.barStyle = .black

        navigationItem.title = "Pass Pitch and Diameters"
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "Home_2x").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleDismiss))

    


【讨论】:

以上是关于以编程方式创建 VC,使用公式中文本字段中的整数并在点击 UIButton 时执行计算的主要内容,如果未能解决你的问题,请参考以下文章

总结以编程方式创建的编辑文本中的所有十进制值

以编程方式选择输入字段中的部分文本

如何使用公式在单元格文本中间创建超链接?

以编程方式在 xib 上使用自动布局创建的两个文本字段之间添加 uiview

以编程方式将文本字段值传递给另一个视图中的标签

如何以编程方式添加文本字段和按钮?