Created
February 10, 2020 08:21
-
-
Save donguri9/41d6b0a6f5509a2294329f78e2d98a19 to your computer and use it in GitHub Desktop.
2020/02/10
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
class CalcViewModel:ObservableObject{ | |
@Published var display = "0" | |
@Published var middleTyping = false | |
var displayValue:Double{ | |
get{ | |
return Double(display)! | |
} | |
set{ | |
display = String(newValue) | |
} | |
} | |
} | |
struct ContentView: View { | |
@EnvironmentObject var calcVM: CalcViewModel | |
var body: some View { | |
VStack(spacing:10){ | |
Text(calcVM.display) | |
.font(.largeTitle) | |
.padding(.all) | |
.frame(maxWidth:280,alignment: .trailing) | |
.border(Color.red) | |
.padding(.leading) | |
.padding(.trailing) | |
HStack{ | |
UnarySymbols() | |
Digits() | |
// UnarySymbols(display:$calcVM.display) | |
// Digits(display:$calcVM.display) | |
} | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct UnarySymbols:View { | |
@EnvironmentObject var calcVM: CalcViewModel | |
let symbols = ["π","√","±","="] | |
var body:some View{ | |
VStack(spacing:10){ | |
ForEach(symbols,id:\.self){mathSymbol in | |
Button(mathSymbol,action:{ | |
self.performOperation(mathSymbol) | |
}) | |
.frame(width:60,height: 60) | |
.border(Color.red) | |
.font(.largeTitle) | |
} | |
} | |
} | |
func performOperation(_ symbol:String){ | |
switch symbol { | |
case "π": | |
calcVM.displayValue = Double.pi | |
self.calcVM.middleTyping = false | |
case "√": | |
calcVM.displayValue = sqrt(calcVM.displayValue) | |
self.calcVM.middleTyping = false | |
default: | |
break | |
} | |
} | |
} | |
struct Digits: View { | |
@EnvironmentObject var calcVM: CalcViewModel | |
let digits = [[7,8,9], | |
[4,5,6], | |
[3,2,1], | |
[0]] | |
@State var middleTyping = false | |
var body: some View { | |
VStack(spacing:10){ | |
ForEach(digits,id:\.self){rowDigits in | |
HStack(spacing:12){ | |
ForEach(rowDigits,id:\.self){digit in | |
Button("\(digit)", action:{ | |
if self.calcVM.middleTyping{ | |
self.calcVM.display = self.calcVM.display + "\(digit)" | |
}else{ | |
self.calcVM.display = "\(digit)" | |
self.calcVM.middleTyping = true | |
} | |
}) | |
.frame(width:60,height: 60) | |
.border(Color.red) | |
.font(.largeTitle) | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment