分段控制器问题

时间:2015-07-14 09:49:01

标签: swift uisegmentedcontrol

enter image description here

我上面的段控制器连接到下面的代码。

@IBOutlet weak var coatSegmentController: UISegmentedControl!

@IBAction func coatSelectInput() {

        switch (self.unitSegmentController.selectedSegmentIndex) {

        case 0:
            coatSetter = 1
            //println("SWITCHED TO coat 1")
            println(unitSegmentController.selectedSegmentIndex)

        case 1:
            coatSetter = 2
            //println("SWITCHED TO coat 2")
            println(unitSegmentController.selectedSegmentIndex)

        case 2:
            coatSetter = 3
            //println("SWITCHED TO coat 3")
            println(unitSegmentController.selectedSegmentIndex)

        default:
            println("Coat switch did not work")

        }


    }

无论我选择哪个片段,它总是返回我选择的第一个片段。

如果我将它挂在我的单位分段插座上,它就能正常工作。但随后单位停止工作。

@IBOutlet weak var unitSegmentController: UISegmentedControl!

知道那是什么意思吗?我已经尝试了一切。多次删除并重新创建。似乎没什么用。

以下是该视图的完整代码。

import UIKit
import CoreData

class PaintViewController: UIViewController, UITextFieldDelegate {

    //FIELDS *********************************************************

    @IBOutlet weak var widthField: UITextField!
    @IBOutlet weak var heigthField: UITextField!
    @IBOutlet weak var basecoatPriceField: UITextField!
    @IBOutlet weak var basecoatCanSizeField: UITextField!
    @IBOutlet weak var topcoatPriceField: UITextField!
    @IBOutlet weak var topcoatCanSizeField: UITextField!

    //FIELD LABELS ***************************************************


    @IBOutlet weak var areaToPaintHeader: UILabel!
    @IBOutlet weak var basecoatPriceHeader: UILabel!
    @IBOutlet weak var topcoatHeader: UILabel!

    @IBOutlet weak var basecoatUnit: UILabel!
    @IBOutlet weak var topcoatUnit: UILabel!

    //RESULT LABELS

    @IBOutlet weak var resultBasecoatUnit: UILabel!
    @IBOutlet weak var resultBasecoatAmount: UILabel!
    @IBOutlet weak var resultBasecoatCost: UILabel!
    @IBOutlet weak var resultTopcoatUnit: UILabel!
    @IBOutlet weak var resultTopcoatAmount: UILabel!
    @IBOutlet weak var resultTopcoatCost: UILabel!
    @IBOutlet weak var basecoatNoCostWarning: UILabel!
    @IBOutlet weak var topcoatNoCostWarning: UILabel!

    // OTHER CONTROLERS

    @IBOutlet weak var whatthehell: UISegmentedControl!
    @IBOutlet weak var coatSegmentController: UISegmentedControl!
    @IBOutlet weak var mainScrollView: UIScrollView!
    @IBOutlet weak var unitSegmentController: UISegmentedControl!

//    @IBOutlet weak var coatSegController: UISegmentedControl!

    // INSTANCES ******************************************************

    var unitSetter = "metric"
    var coatSetter = 1

    //CREATE CONCRETE CORE DATA OBJECT
    var paint = [PaintEntity]()

    let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

    //    var calculations = PaintModel(
    //        width: 0.0,
    //        heigth: 0.0,
    //        basecoatPrice: 0.0,
    //        basecoatCanAmount: 0.0,
    //        topcoatPrice: 0.0,
    //        topcoatCanAmount: 0.0,
    //        unit: "metric",
    //        coats: 1.0)


    // ******************************************************************
    // NATIVE METHODS
    // ******************************************************************

    override func viewDidLoad() {
        super.viewDidLoad()

        //Empty cost warning label
        basecoatNoCostWarning.text = ""
        topcoatNoCostWarning.text = ""

        // RESET CAN
        basecoatCanSizeField.text = "5.0"
        topcoatCanSizeField.text = "5.0"
        //        calculations.basecoatCanAmount = 5.0
        //        calculations.topcoatCanAmount = 5.0


        // APPLY ICON
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 31, height: 36))
        imageView.contentMode = .ScaleAspectFit
        let image = UIImage(named: "concrete_bag_detail")
        imageView.image = image
        navigationItem.titleView = imageView

        // NAV BAR BG CUSTOM ********************

        var navBarColor = navigationController!.navigationBar

        // BG COLOR
        navBarColor.barTintColor = UIColor(hue: 162/360.0, saturation: 80/100.0, brightness: 45/100.0, alpha: 100.0/100.0)

        navBarColor.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blackColor()]

        // STATUS BAR WHITE COLOR ********************
        UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent

        // DETECT TAP TO TRIGGER HIDE KEYBOARD

        let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideKeyboard")
        tapGesture.cancelsTouchesInView = false
        mainScrollView.addGestureRecognizer(tapGesture)


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // ******************************************************************
    // MY METHODS
    // ******************************************************************



    // RESET ******************************************************

    //    func resetDataModel (){
    //
    ////        calculations.width = 0.0
    ////        calculations.heigth = 0.0
    ////        calculations.basecoatPrice = 0.0
    ////        calculations.basecoatCanAmount = 0.0
    ////        calculations.topcoatPrice = 0.0
    ////        calculations.topcoatCanAmount = 0.0
    //
    //    }

    func resetInputAndLabels(){


        widthField.text =  ""
        heigthField.text =  ""
        basecoatPriceField.text =  ""
        topcoatPriceField.text =  ""

        basecoatNoCostWarning.text =  ""
        topcoatNoCostWarning.text =  ""

        resultBasecoatAmount.text = "0.0"
        resultBasecoatCost.text = "$0.00"
        resultTopcoatAmount.text = "0.0"
        resultTopcoatCost.text = "$0.00"


        switch unitSetter {

        case "metric":

            basecoatCanSizeField.text =  "5.0"
            topcoatCanSizeField.text =  "5.0"
            basecoatUnit.text = "litre can"
            topcoatUnit.text = "litre can"
            resultBasecoatUnit.text = "Litres"
            resultTopcoatUnit.text = "Litres"


        case "imperial":

            basecoatCanSizeField.text =  "1.0"
            topcoatCanSizeField.text =  "1.0"
            basecoatUnit.text = "gal can"
            topcoatUnit.text = "gal can"
            resultBasecoatUnit.text = "Gallons"
            resultTopcoatUnit.text = "Gallons"


        default:
            println("Not able to reset labels")
        }

    }


    //ALERT VIEW METHODS  ******************************************************


    func alertViewLaunch (#message: String){

        var alertView = UIAlertView(title: "Ops!", message: message, delegate: self, cancelButtonTitle: "Ok,got it!")

        alertView.show()

    }


    //KEYBOARD RESIZE VIEW  ******************************************

    // Call this method somewhere in your view controller setup code.
    func registerForKeyboardNotifications() {
        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(self,
            selector: "keyboardWillBeShown:",
            name: UIKeyboardWillShowNotification,
            object: nil)
        notificationCenter.addObserver(self,
            selector: "keyboardWillBeHidden:",
            name: UIKeyboardWillHideNotification,
            object: nil)
    }

    // Called when the UIKeyboardDidShowNotification is sent.
    func keyboardWillBeShown(sender: NSNotification) {
        let info: NSDictionary = sender.userInfo!
        let value: NSValue = info.valueForKey(UIKeyboardFrameBeginUserInfoKey) as! NSValue
        let keyboardSize: CGSize = value.CGRectValue().size
        let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0)
        mainScrollView.contentInset = contentInsets
        mainScrollView.scrollIndicatorInsets = contentInsets

        // If active text field is hidden by keyboard, scroll it so it's visible
        // Your app might not need or want this behavior.
        var aRect: CGRect = self.view.frame
        aRect.size.height -= keyboardSize.height

    }

    // Called when the UIKeyboardWillHideNotification is sent
    func keyboardWillBeHidden(sender: NSNotification) {
        let contentInsets: UIEdgeInsets = UIEdgeInsetsZero
        mainScrollView.contentInset = contentInsets
        mainScrollView.scrollIndicatorInsets = contentInsets
    }


    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.registerForKeyboardNotifications()
    }

    override func viewDidDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }


    // HIDE KEYBOARD ON TOUCH ****************************************

    func hideKeyboard(){

        widthField.resignFirstResponder()
        heigthField.resignFirstResponder()
        basecoatPriceField.resignFirstResponder()
        topcoatPriceField.resignFirstResponder()
        basecoatCanSizeField.resignFirstResponder()
        topcoatCanSizeField.resignFirstResponder()

    }


    // *********************************************************************************
    // ACTIONS
    // *********************************************************************************



    @IBAction func resetButton() {

        resetInputAndLabels()
        //        resetDataModel()
    }

    // CHANGE UNIT **************************************************

    @IBAction func unitSelectInput() {

        switch unitSegmentController.selectedSegmentIndex {

        case 0:
            unitSetter = "metric"
            resetInputAndLabels()
            //            resetDataModel()
            //println("SWITCHED TO metric")
                        println(unitSegmentController.selectedSegmentIndex)

        case 1:
            unitSetter = "imperial"
            resetInputAndLabels()
            //            resetDataModel()
            //println("SWITCH TO imperial")
                        println(unitSegmentController.selectedSegmentIndex)

        default:
            println("Unit switch did not work")

        }
    }

    // CHANGE COAT **********************************************

    @IBAction func coatSelectInput() {

        switch (self.unitSegmentController.selectedSegmentIndex) {

        case 0:
            coatSetter = 1
            //println("SWITCHED TO coat 1")
            println(unitSegmentController.selectedSegmentIndex)

        case 1:
            coatSetter = 2
            //println("SWITCHED TO coat 2")
            println(unitSegmentController.selectedSegmentIndex)

        case 2:
            coatSetter = 3
            //println("SWITCHED TO coat 3")
            println(unitSegmentController.selectedSegmentIndex)

        default:
            println("Coat switch did not work")

        }


    }

    // GENERATE RESULTS **********************************************

    @IBAction func generateResults() {

        //SCROLL VIEW TO SHOW RESULTS - Only for 4s

        let screenSize: CGRect = UIScreen.mainScreen().bounds

        //println("Screen heigth - \(screenSize.height)")

        if screenSize.height <= 480 {

            UIScrollView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 1.5, initialSpringVelocity: 1.5, options: UIViewAnimationOptions.CurveLinear, animations: {
                self.mainScrollView.contentOffset.y = 220.0

                }, completion: {
                    Void in
                    UIView.animateWithDuration(0.6, delay: 0.0, usingSpringWithDamping: 0.1, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveLinear, animations: {}, completion: { Void in })
            })
        }


        //SAVE TO COREDATA
        //DETECT IF NO DATA HAS BEEN ENTERED

        if widthField.text == "" || heigthField.text == "" || basecoatCanSizeField.text == "" || topcoatCanSizeField.text == "" {

            alertViewLaunch(message: "I will need at least width, heigth, basecoat can size and topcoat can size to get the basic calculations done")

        } else {

            //STORE DATA DEPENDING ON UNIT
            switch unitSetter {

            case "metric": PaintEntity.createInManagedObjectContext(self.managedObjectContext!,
                width: NSString(string: (widthField.text)).doubleValue,
                heigth: NSString(string: (heigthField.text)).doubleValue,
                basecoatPrice: NSString(string: (basecoatPriceField.text)).doubleValue,
                basecoatCanSize: NSString(string: (basecoatCanSizeField.text)).doubleValue,
                topcoatPrice: NSString(string: (topcoatPriceField.text)).doubleValue,
                topcoatCanSize: NSString(string: (topcoatCanSizeField.text)).doubleValue,
                unit: "metric",
                coats: coatSetter)

            case "imperial":PaintEntity.createInManagedObjectContext(self.managedObjectContext!,
                width: NSString(string: (widthField.text)).doubleValue,
                heigth: NSString(string: (heigthField.text)).doubleValue,
                basecoatPrice: NSString(string: (basecoatPriceField.text)).doubleValue,
                basecoatCanSize: NSString(string: (basecoatCanSizeField.text)).doubleValue,
                topcoatPrice: NSString(string: (topcoatPriceField.text)).doubleValue,
                topcoatCanSize: NSString(string: (topcoatCanSizeField.text)).doubleValue,
                unit: "imperial",
                coats: coatSetter)

            default:
                println("No unit detected")

            }
            printResults()
        }
    }

    func printResults(){

        let fetchRequest = NSFetchRequest(entityName: "PaintEntity")

        let sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
        fetchRequest.sortDescriptors = [sortDescriptor]
        fetchRequest.fetchLimit = 1
        var error : NSError?

        if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: &error) as? [PaintEntity] {

            resultBasecoatAmount.text = "\(roundNumberToOne(fetchResults[0].resultBasecoatAmount.doubleValue))"
            resultTopcoatAmount.text = "\(roundNumberToOne(fetchResults[0].resultTopcoatAmount.doubleValue))"

            //println("I am fetching this \(fetchResults[0])")

            if basecoatPriceField.text == "" || topcoatPriceField.text == "" {

                resultBasecoatCost.textColor = UIColor(hue: 162/360.0, saturation: 65/100.0, brightness: 45/100.0, alpha: 100.0/100.0)
                basecoatNoCostWarning.text = "Missing price"
                resultBasecoatCost.text = "$0.00"

                resultTopcoatCost.textColor = UIColor(hue: 162/360.0, saturation: 65/100.0, brightness: 45/100.0, alpha: 100.0/100.0)
                topcoatNoCostWarning.text = "Missing price"
                resultTopcoatCost.text = "$0.00"

            }else{

                if basecoatPriceField == "" {
                    resultBasecoatCost.textColor = UIColor(hue: 162/360.0, saturation: 65/100.0, brightness: 45/100.0, alpha: 100.0/100.0)
                    basecoatNoCostWarning.text = "Missing price"
                    resultBasecoatCost.text = "$0.00"

                } else {

                    resultBasecoatCost.textColor = UIColor.whiteColor()
                    basecoatNoCostWarning.text = ""
                    resultBasecoatCost.text = "$\(roundNumberToTwo(fetchResults[0].resultBasecoatCost.doubleValue))"

                }

                if topcoatPriceField == "" {
                    resultTopcoatCost.textColor = UIColor(hue: 165/360.0, saturation: 63/100.0, brightness: 53/100.0, alpha: 100.0/100.0)
                    topcoatNoCostWarning.text = "Missing price"
                    resultTopcoatCost.text = "$0.00"

                }else{

                    resultTopcoatCost.textColor = UIColor.whiteColor()
                    topcoatNoCostWarning.text = ""
                    resultTopcoatCost.text = "$\(roundNumberToTwo(fetchResults[0].resultTopcoatCost.doubleValue))"
                }
            }
        }
    }
}

0 个答案:

没有答案