help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
swift-ios-calculator
RSK World
swift-ios-calculator
Swift iOS Calculator v1.0 - AI Math Solver + 3D Graphing + Apple Watch Integration + iOS Widgets + Siri Shortcuts + Currency Converter + Scientific Calculator + Matrix Operations + Platform Integration + Modern iOS Development
swift-ios-calculator
  • Assets.xcassets
  • Base.lproj
  • swift-ios-calculator.xcodeproj
  • AIMathSolverViewController.swift26.6 KB
  • AppDelegate.swift1.7 KB
  • CalculatorHistoryViewController.swift6.5 KB
  • CalculatorLogic.swift4.4 KB
  • CalculatorSettingsViewController.swift5.6 KB
  • CalculatorTheme.swift8.3 KB
  • CalculatorUtils.swift6.9 KB
  • CalculatorViewController.swift3.4 KB
  • CalculatorWidget.swift14.3 KB
  • CalculatorWidgetInfo.plist846 B
  • ChemistryCalculatorViewController.swift26.9 KB
  • CurrencyConverterViewController.swift13.3 KB
  • CustomFormulaBuilderViewController.swift22.1 KB
  • EngineeringCalculatorViewController.swift25.7 KB
  • EquationSolverViewController.swift22.8 KB
  • FinancialCalculatorViewController.swift27.5 KB
  • GeometryCalculatorViewController.swift29.7 KB
  • Graphing3DViewController.swift20.8 KB
  • GraphingCalculatorViewController.swift14.7 KB
  • Info.plist3.2 KB
  • LICENSE1.1 KB
  • MainTabBarController.swift22.3 KB
  • MatrixCalculatorViewController.swift26.6 KB
  • PRIVACY_POLICY.md1.6 KB
  • PhysicsCalculatorService.swift8.2 KB
  • ProgrammerCalculatorViewController.swift11 KB
  • README.md8.7 KB
  • RELEASE_NOTES.md6.5 KB
  • SceneDelegate.swift2.8 KB
  • ScientificCalculatorViewController.swift6.2 KB
  • SiriShortcutsManager.swift23.5 KB
  • Swift iOS Calculator.entitlements1.1 KB
  • UnitConverterViewController.swift14 KB
  • WatchCalculatorViewController.swift15.3 KB
  • index.html47.5 KB
GraphingCalculatorViewController.swift
GraphingCalculatorViewController.swift
Raw Download
Find: Go to:
//
//  GraphingCalculatorViewController.swift
//  Swift iOS Calculator
//
//  Created by RSK World on 23/01/2026.
//  Copyright © 2026 RSK World. All rights reserved.
//
//  Developer: Molla Samser (Founder, RSK World)
//  Designer & Tester: Rima Khatun
//  Contact: info@rskworld.com, +91 93305 39277
//  Website: https://rskworld.in
//  Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India - 713147
//

import UIKit
import CoreGraphics

class GraphingCalculatorViewController: UIViewController {
    
    // MARK: - Outlets
    @IBOutlet weak var graphView: GraphView!
    @IBOutlet weak var functionTextField: UITextField!
    @IBOutlet weak var xMinTextField: UITextField!
    @IBOutlet weak var xMaxTextField: UITextField!
    @IBOutlet weak var yMinTextField: UITextField!
    @IBOutlet weak var yMaxTextField: UITextField!
    @IBOutlet weak var plotButton: UIButton!
    @IBOutlet weak var clearButton: UIButton!
    @IBOutlet weak var zoomInButton: UIButton!
    @IBOutlet weak var zoomOutButton: UIButton!
    @IBOutlet weak var resetButton: UIButton!
    @IBOutlet weak var functionSegmentedControl: UISegmentedControl!
    
    // MARK: - Properties
    private var functions: [String] = []
    private var colors: [UIColor] = [.systemBlue, .systemRed, .systemGreen, .systemOrange, .systemPurple, .systemPink]
    private var currentFunctionIndex = 0
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupGraphView()
    }
    
    // MARK: - Setup
    private func setupUI() {
        title = "Graphing Calculator"
        view.backgroundColor = CalculatorTheme.shared.backgroundColor
        
        // Setup text fields
        setupTextField(functionTextField, placeholder: "Enter function (e.g., x^2, sin(x), cos(x))")
        setupTextField(xMinTextField, placeholder: "-10")
        setupTextField(xMaxTextField, placeholder: "10")
        setupTextField(yMinTextField, placeholder: "-10")
        setupTextField(yMaxTextField, placeholder: "10")
        
        // Set default values
        xMinTextField.text = "-10"
        xMaxTextField.text = "10"
        yMinTextField.text = "-10"
        yMaxTextField.text = "10"
        
        // Setup buttons
        setupButton(plotButton, title: "Plot", color: .systemGreen)
        setupButton(clearButton, title: "Clear", color: .systemRed)
        setupButton(zoomInButton, title: "Zoom In", color: .systemBlue)
        setupButton(zoomOutButton, title: "Zoom Out", color: .systemBlue)
        setupButton(resetButton, title: "Reset", color: .systemGray)
        
        // Setup segmented control
        functionSegmentedControl.backgroundColor = CalculatorTheme.shared.buttonBackgroundColor
        functionSegmentedControl.selectedSegmentTintColor = CalculatorTheme.shared.accentColor
        functionSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: CalculatorTheme.shared.textColor], for: .normal)
        functionSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
    }
    
    private func setupTextField(_ textField: UITextField, placeholder: String) {
        textField.backgroundColor = CalculatorTheme.shared.displayBackgroundColor
        textField.textColor = CalculatorTheme.shared.textColor
        textField.placeholder = placeholder
        textField.layer.cornerRadius = 8
        textField.layer.borderWidth = 1
        textField.layer.borderColor = CalculatorTheme.shared.buttonBackgroundColor.cgColor
        textField.textAlignment = .center
    }
    
    private func setupButton(_ button: UIButton, title: String, color: UIColor) {
        button.setTitle(title, for: .normal)
        button.backgroundColor = color
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 8
    }
    
    private func setupGraphView() {
        graphView.backgroundColor = CalculatorTheme.shared.displayBackgroundColor
        graphView.layer.cornerRadius = 12
        graphView.layer.borderWidth = 2
        graphView.layer.borderColor = CalculatorTheme.shared.buttonBackgroundColor.cgColor
    }
    
    // MARK: - Actions
    @IBAction func plotButtonPressed(_ sender: UIButton) {
        guard let function = functionTextField.text, !function.isEmpty else {
            showAlert(message: "Please enter a function to plot")
            return
        }
        
        guard let xMin = Double(xMinTextField.text ?? ""),
              let xMax = Double(xMaxTextField.text ?? ""),
              let yMin = Double(yMinTextField.text ?? ""),
              let yMax = Double(yMaxTextField.text ?? "") else {
            showAlert(message: "Please enter valid numeric values for the range")
            return
        }
        
        if xMin >= xMax || yMin >= yMax {
            showAlert(message: "Minimum values must be less than maximum values")
            return
        }
        
        // Add function to list
        if currentFunctionIndex >= functions.count {
            functions.append(function)
        } else {
            functions[currentFunctionIndex] = function
        }
        
        // Update segmented control
        if currentFunctionIndex >= functionSegmentedControl.numberOfSegments {
            functionSegmentedControl.insertSegment(withTitle: "f\(currentFunctionIndex + 1)(x)", at: currentFunctionIndex, animated: true)
        }
        functionSegmentedControl.selectedSegmentIndex = currentFunctionIndex
        
        // Plot the function
        plotFunction(function, xMin: xMin, xMax: xMax, yMin: yMin, yMax: yMax)
        
        // Move to next function
        currentFunctionIndex = (currentFunctionIndex + 1) % 6
        functionTextField.text = ""
    }
    
    @IBAction func clearButtonPressed(_ sender: UIButton) {
        graphView.clearGraph()
        functions.removeAll()
        currentFunctionIndex = 0
        
        // Clear segmented control
        while functionSegmentedControl.numberOfSegments > 0 {
            functionSegmentedControl.removeSegment(at: 0, animated: true)
        }
    }
    
    @IBAction func zoomInButtonPressed(_ sender: UIButton) {
        guard let xMin = Double(xMinTextField.text ?? ""),
              let xMax = Double(xMaxTextField.text ?? ""),
              let yMin = Double(yMinTextField.text ?? ""),
              let yMax = Double(yMaxTextField.text ?? "") else { return }
        
        let xCenter = (xMin + xMax) / 2
        let yCenter = (yMin + yMax) / 2
        let xRange = (xMax - xMin) * 0.4
        let yRange = (yMax - yMin) * 0.4
        
        xMinTextField.text = String(xCenter - xRange)
        xMaxTextField.text = String(xCenter + xRange)
        yMinTextField.text = String(yCenter - yRange)
        yMaxTextField.text = String(yCenter + yRange)
        
        replotAllFunctions()
    }
    
    @IBAction func zoomOutButtonPressed(_ sender: UIButton) {
        guard let xMin = Double(xMinTextField.text ?? ""),
              let xMax = Double(xMaxTextField.text ?? ""),
              let yMin = Double(yMinTextField.text ?? ""),
              let yMax = Double(yMaxTextField.text ?? "") else { return }
        
        let xCenter = (xMin + xMax) / 2
        let yCenter = (yMin + yMax) / 2
        let xRange = (xMax - xMin) * 0.6
        let yRange = (yMax - yMin) * 0.6
        
        xMinTextField.text = String(xCenter - xRange)
        xMaxTextField.text = String(xCenter + xRange)
        yMinTextField.text = String(yCenter - yRange)
        yMaxTextField.text = String(yCenter + yRange)
        
        replotAllFunctions()
    }
    
    @IBAction func resetButtonPressed(_ sender: UIButton) {
        xMinTextField.text = "-10"
        xMaxTextField.text = "10"
        yMinTextField.text = "-10"
        yMaxTextField.text = "10"
        replotAllFunctions()
    }
    
    @IBAction func functionChanged(_ sender: UISegmentedControl) {
        currentFunctionIndex = sender.selectedSegmentIndex
        if currentFunctionIndex < functions.count {
            functionTextField.text = functions[currentFunctionIndex]
        }
    }
    
    // MARK: - Methods
    private func plotFunction(_ function: String, xMin: Double, xMax: Double, yMin: Double, yMax: Double) {
        let points = calculatePoints(for: function, xMin: xMin, xMax: xMax, yMin: yMin, yMax: yMax)
        let color = colors[currentFunctionIndex % colors.count]
        graphView.plotFunction(points: points, color: color, xMin: xMin, xMax: xMax, yMin: yMin, yMax: yMax)
    }
    
    private func calculatePoints(for function: String, xMin: Double, xMax: Double, yMin: Double, yMax: Double) -> [CGPoint] {
        var points: [CGPoint] = []
        let steps = 500
        let stepSize = (xMax - xMin) / Double(steps)
        
        for i in 0...steps {
            let x = xMin + Double(i) * stepSize
            let y = evaluateFunction(function, at: x)
            
            if !y.isNaN && !y.isInfinite && y >= yMin && y <= yMax {
                let normalizedX = (x - xMin) / (xMax - xMin)
                let normalizedY = 1.0 - (y - yMin) / (yMax - yMin)
                points.append(CGPoint(x: normalizedX, y: normalizedY))
            }
        }
        
        return points
    }
    
    private func evaluateFunction(_ function: String, at x: Double) -> Double {
        let expression = function.lowercased()
            .replacingOccurrences(of: "x", with: "(\(x))")
            .replacingOccurrences(of: "^", with: "**")
            .replacingOccurrences(of: "sin", with: "Foundation.sin")
            .replacingOccurrences(of: "cos", with: "Foundation.cos")
            .replacingOccurrences(of: "tan", with: "Foundation.tan")
            .replacingOccurrences(of: "log", with: "Foundation.log")
            .replacingOccurrences(of: "ln", with: "Foundation.log")
            .replacingOccurrences(of: "sqrt", with: "Foundation.sqrt")
            .replacingOccurrences(of: "abs", with: "Foundation.abs")
            .replacingOccurrences(of: "exp", with: "Foundation.exp")
            .replacingOccurrences(of: "pi", with: "Double.pi")
            .replacingOccurrences(of: "e", with: "Foundation.exp(1)")
        
        let expressionParser = ExpressionParser()
        return expressionParser.evaluate(expression)
    }
    
    private func replotAllFunctions() {
        guard let xMin = Double(xMinTextField.text ?? ""),
              let xMax = Double(xMaxTextField.text ?? ""),
              let yMin = Double(yMinTextField.text ?? ""),
              let yMax = Double(yMaxTextField.text ?? "") else { return }
        
        graphView.clearGraph()
        
        for (index, function) in functions.enumerated() {
            let points = calculatePoints(for: function, xMin: xMin, xMax: xMax, yMin: yMin, yMax: yMax)
            let color = colors[index % colors.count]
            graphView.plotFunction(points: points, color: color, xMin: xMin, xMax: xMax, yMin: yMin, yMax: yMax)
        }
    }
    
    private func showAlert(message: String) {
        let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

// MARK: - GraphView
class GraphView: UIView {
    
    private var functionPaths: [UIBezierPath] = []
    private var functionColors: [UIColor] = []
    private var xMin: Double = -10
    private var xMax: Double = 10
    private var yMin: Double = -10
    private var yMax: Double = 10
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        guard let context = UIGraphicsGetCurrentContext() else { return }
        
        // Draw grid
        drawGrid(in: context, rect: rect)
        
        // Draw axes
        drawAxes(in: context, rect: rect)
        
        // Draw functions
        for (index, path) in functionPaths.enumerated() {
            functionColors[index].setStroke()
            path.lineWidth = 2.0
            path.stroke()
        }
    }
    
    private func drawGrid(in context: CGContext, rect: CGRect) {
        context.setStrokeColor(UIColor.systemGray4.cgColor)
        context.setLineWidth(0.5)
        
        // Vertical lines
        for i in 0...10 {
            let x = rect.width * CGFloat(i) / 10.0
            context.move(to: CGPoint(x: x, y: 0))
            context.addLine(to: CGPoint(x: x, y: rect.height))
        }
        
        // Horizontal lines
        for i in 0...10 {
            let y = rect.height * CGFloat(i) / 10.0
            context.move(to: CGPoint(x: 0, y: y))
            context.addLine(to: CGPoint(x: rect.width, y: y))
        }
        
        context.strokePath()
    }
    
    private func drawAxes(in context: CGContext, rect: CGRect) {
        context.setStrokeColor(UIColor.label.cgColor)
        context.setLineWidth(2.0)
        
        // X-axis
        let yZero = rect.height * CGFloat((yMax) / (yMax - yMin))
        context.move(to: CGPoint(x: 0, y: yZero))
        context.addLine(to: CGPoint(x: rect.width, y: yZero))
        
        // Y-axis
        let xZero = rect.width * CGFloat((-xMin) / (xMax - xMin))
        context.move(to: CGPoint(x: xZero, y: 0))
        context.addLine(to: CGPoint(x: xZero, y: rect.height))
        
        context.strokePath()
    }
    
    func plotFunction(points: [CGPoint], color: UIColor, xMin: Double, xMax: Double, yMin: Double, yMax: Double) {
        self.xMin = xMin
        self.xMax = xMax
        self.yMin = yMin
        self.yMax = yMax
        
        let path = UIBezierPath()
        
        for (index, point) in points.enumerated() {
            let x = point.x * bounds.width
            let y = point.y * bounds.height
            
            if index == 0 {
                path.move(to: CGPoint(x: x, y: y))
            } else {
                path.addLine(to: CGPoint(x: x, y: y))
            }
        }
        
        functionPaths.append(path)
        functionColors.append(color)
        setNeedsDisplay()
    }
    
    func clearGraph() {
        functionPaths.removeAll()
        functionColors.removeAll()
        setNeedsDisplay()
    }
}

// MARK: - Expression Parser
class ExpressionParser {
    
    func evaluate(_ expression: String) -> Double {
        // Simple expression evaluator
        // In a real app, you'd use a more sophisticated parser
        let nsExpression = NSExpression(format: expression)
        return nsExpression.expressionValue(with: nil, context: nil) as? Double ?? 0.0
    }
}
382 lines•14.7 KB
swift

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer