battle programmers alliance
Would you like to react to this message? Create an account in a few clicks or log in to continue.

battle programmers allianceLog in

the LivinGrimoire Artificial General Intelligence software design pattern forum

ios app dev

power_settings_newLogin to reply
2 posters

descriptionios app dev Emptyios app dev

more_horiz
ios app dev 2lf3xh


online swift playground :

http://online.swiftplayground.run/

on a macOS 10.12.6 or later device DL latest versions of both the iOS SDK and Xcode can be
downloaded free of charge from the Mac App Store (search and install xcode)

add your appleID to your Xcode :
Xcode -> Preferences... menu option and select the Accounts tab
On the Accounts screen, click on the + button select Apple IDfrom the resulting panel, continue
When prompted, enter your Apple ID and associated password and click on the Sign In
button to add the account to the preferences

enroll as a developer, and get access to forums and test devices :
https://developer.apple.com/programs/enroll/

Developer(not enrolled as a developer) and Distribution(if you enrolled as a developer)
Signing Identities :

view current signing identities : select the
newly added Apple ID in the Accounts panel and click on the Manage Certificates
To create the iOS Development signing identity : click on the + button and choose
iOS dev or distribution option

OOP :

declare a class : class NewClassName{}

open Xcode, Create a new Xcode project, single view app :

development team : if you havent enrolled as an Apple developer program set to none
Organization Name field : used for copyrights
company identifier = reverse URL : com.yotamrker
set PL(prog lang) to swift

the Main.storyboard file is the UI screen to drag drop controllers into


swift online IDE : http://online.swiftplayground.run/
or from Xcode choose open playgraound which is an IDE for testing code snippets
and practicing swift

make Xcode dark theme : toolbar, Xcode, pref, fonts and colors

declare var :
the compiler deduces var type

var mynumber = 10
var myChar4 = "\u{0058}"

explicit var declare : var x : Int = 10

print("Int32 Min= \(Int32.min) Int32 Max = \(Int32.max)")

outputs : Int32
Min = -2147483648 Int32 Max = 2147483647

const : let maxCount = 100

string megazord :

var message = "\(userName) has \(inboxCount) message. Message capacity remaining is \(maxCount -inboxCount)"

in the () are variables
output :

print(message)


declare const : let bookTitle: String

conditional : if Bool {} else{}

simple array program :

simple grade alg with avg, sum :
swift code (run at swift online IDE : http://online.swiftplayground.run/)
Code:

Code:

import Foundation

var grades = [10, 20, 30, 40,50,60,70,80,100,100]
var students = ["one","two","three","four","five","roku","shichi","hachi","kyuu","juu"]
let fail = 55
var sum=0
var max = 0
 print(grades.count)
for idx in 0...grades.count-1
 {
    sum+=grades[idx]
    if max <= grades[idx] {max = grades[idx]}
    if grades[idx] < fail {print("\(students[idx]) has failed")}
 }
 var avg = sum/grades.count
 print("avg grade : \(sum/grades.count)")
 print("highest ranking students :")
for idx in 0...grades.count-1
{
  if max == grades[idx] {print(students[idx])}
}
print("below avg :")
for idx in 0...grades.count-1
{
  if avg > grades[idx] {print(students[idx])}
}


out put :

10
one has failed
two has failed
three has failed
four has failed
five has failed
avg grade : 56
highest ranking students :
kyuu
juu
below avg :
one
two
three
four
five

optional var (could be nil (null)):
var index: Int?
index = 3

var treeArray = ["Oak", "Pine", "Yew", "Birch"]

if index!=nil{print(treeArray[index!])}else{print("nil index")}

to declare a var when you know it will have a value no matter what :
var index: Int! // Optional is now implicitly unwrapped
index = 3
var treeArray = ["Oak", "Pine", "Yew", "Birch"]
if index != nil {print(treeArray[index])} else {print("index doesnot contain a value")}


var multiline = """
digimon
digital monsters, digimon
are the champions !
"""
print(multiline)

special chars :

var newline = "\n"

var backslash = "\\"

for loop :
for i in 1...20{}

comments : // single line
/*
multiline comment
*/

let tuple = (1,"hi",2.5) // tuple var
print(tuple.2)

or


let tuple = (num:1,str:"hi",perc:2.5) // tuple var
print(tuple.num)

or


let tuple = (var1,var2,2.5) // tuple var

var x:Int? // optional var may be nil (null) or something
if x != nil{}
else{}

var y:String?
y = "shouryuken"
var x = ""
x = y! // y converted to string type (unwrapped)
print(x)

or
var y:String?
y = "shouryuken"
var x = ""
if let x = y {print(x)} // as unwrapped
if let y = y, true == true {print(x)} // multi conditional if

as! String // type upcasting

let myButton: UIButton = UIButton()
let myControl = myButton as UIControl // downcasting

check var type :

if myobject is MyClass {
// myobject is an instance of MyClass
}

operators * / + - % (remainder)
short operators :
x %= y

Comparison Operators :
as in java : == > < >= !=

Boolean Logical Operators :
or (||) and (&&) xor (^) not (!)


Range Operators :
x..y
x..<y
one range :
x...
...y

ternary expres​sion(shortened if) :

print("Largest number is \(x > y ? x : y)")

bitwise operator
bit inverter :
let z = ~y
convert 0101 to 1010

no ref loop :

var c = 0
for _ in 1...5 {c +=1}

while loop :

while bool {}

repeat{//statement}
while bool

bresk loop : break
continue loop : continue // jumps to start of next loop


guard <boolean expressions> else {// code to be executed if expression is false<exit statement here>}
// code here is executed if expression is true

import Foundation
func multiplyByTen(value: Int?) {
guard let number = value, number < 10 else {
print("Number is too high")
return
}
let result = number * 10
print(result)
}

multiplyByTen(value:11)

the guard can only live in a function because it has to have a return in its else

switch :

func simpleSwitch(value: Int) {
switch value
{
case 1:
print("one")
case 2:
print("")
case 3,4:
print("3 or 4")
default:
print("case else")
}
}

simpleSwitch(value:1)

a case can also contain a range : case 3...9:
limit the case further : case 3...9 where value == 6:

if no action needed for the default case :
default:
break

methodes :

void function :
func sayHello() {print("Hello")}
sayHello() // summon func

func with params and return :

func buildMessageFor(name: String, count: Int) -> String {
return("\(name), you are customer number \(count)")
}
let message = buildMessageFor(name: "moti", count: 100)
print(message)

use _ when you dont care what the function returns

func buildMessageFor(name: String, count: Int) -> String {
print("moti rulz")
return("\(name), you are customer number \(count)")
}
_ = buildMessageFor(name: "moti", count: 100)


field names exclution in function params :

func buildMessageFor(_ name: String,_ count: Int) -> String {
print("moti rulz")
return("\(name), you are customer number \(count)")
}

_ = buildMessageFor("moti", 100)


you can also replace _ with your preffered name, then summon :
buildMessageFor(x:"John", y:100)

a param can be declared with a default in case you want to pass only one param :

func buildMessageFor(_ name: String = "client", count: Int) -> String {
print("moti rulz")
return("\(name), you are customer number \(count)")
}
print(buildMessageFor(count:100))

returning several vars using a tuple :

Code:

func sizeConverter(_ length: Float) -> (yards: Float, centimeters: Float,meters: Float) {
let yards = length * 0.0277778
let centimeters = length * 2.54
let meters = length * 0.0254
return (yards, centimeters, meters)
}

let lengthTuple = sizeConverter(20)
print(lengthTuple.yards)
print (lengthTuple.centimeters)
print(lengthTuple.meters)


variadic parameters function param :

func displayStrings(_ strings: String...)
{
for string in strings {
print(string)
}
}
displayStrings("one", "two", "three", "four")

sending param by ref :
func doubleValue (_ value: inout Int) -> Int {
value += value
return(value)
}

var myValue = 2
print("doubleValue call returned \(doubleValue(&myValue))")
print(myValue)

POSO class example :

Code:

import Foundation

class BankAccount{
    var accountBalance: Float = 0
    var accountNumber: Int = 0
// c'tor :
init(number: Int, balance: Float)
{
accountNumber = number
accountBalance = balance
}
deinit{
    // code to run when the object is destroyed
}

    func displayBalance(){
print("Number \(accountNumber)")
print("Current balance is \(accountBalance)")}

class func getMaxBalance() -> Float {
return 100000.00} // static function
}
// var account1: BankAccount = BankAccount() // usable without constructor (default c'tor)
var account1: BankAccount = BankAccount(number:1,balance: 1005)
account1.accountBalance = 2005 // access var in the class
account1.displayBalance()
print(BankAccount.getMaxBalance())


getters and setters :

class BankAccount {
var accountBalance: Float = 0
var accountNumber: Int = 0;
let fees: Float = 25.00

var balanceLessFees: Float {get {return accountBalance - fees}
set(newBalance){accountBalance = newBalance - fees}}

init(number: Int, balance: Float)
{
accountNumber = number
accountBalance = balance
}
}

var account1: BankAccount = BankAccount(number:1,balance: 1005)
var balance1 = account1.balanceLessFees // input from getter
print(balance1)
account1.balanceLessFees = 3000
print(account1.balanceLessFees)// output from setter

self (in java this. ) :

class MyClass {
var myNumber = 1
func addTen() {
self.myNumber += 10
}
}

var x = MyClass()
x.addTen()
print(x.myNumber) // output 11


// inheritance example
class BankAccount{
var accountBalance: Float = 0
var accountNumber: Int = 0
// c'tor :
init(number: Int, balance: Float)
{
accountNumber = number
accountBalance = balance
}
func displayBalance(){
print("Number \(accountNumber)")
print("Current balance is \(accountBalance)")}
}

class SavingsAccount: BankAccount {
var interestRate: Float = 0.0
func calculateInterest() -> Float{return interestRate * accountBalance}
}

var x = SavingsAccount(number: 10, balance:20)
x.interestRate = 5
print(x.calculateInterest())

*********************************************************************************

Code:

import Foundation
// inheritance with override
class BankAccount{
    var accountBalance: Float = 0
    var accountNumber: Int = 0
// c'tor :
init(number: Int, balance: Float)
{
accountNumber = number
accountBalance = balance
}
    func displayBalance(){
print("Number \(accountNumber)")
print("Current balance is \(accountBalance)")}
}

class SavingsAccount: BankAccount {
    var interestRate: Float = 0.0
func calculateInterest() -> Float{return interestRate * accountBalance}
override func displayBalance(){
print("Number \(accountNumber)")
print("Current balance is \(accountBalance)")
print("Prevailing interest rate is \(interestRate)")}
}

var x = SavingsAccount(number: 10, balance:20)
x.interestRate = 5
x.displayBalance()


**********************************************************************************

override methode with super :

override func displayBalance(){
super.displayBalance()
print("Prevailing interest rate is \(interestRate)")
}
}

************************************************************************

subclass c'tor + initializing its instance :

import Foundation
// inheritance with override
class BankAccount{
var accountBalance: Float = 0
var accountNumber: Int = 0
// c'tor :
init(number: Int, balance: Float)
{
accountNumber = number
accountBalance = balance
}
func displayBalance(){
print("Number \(accountNumber)")
print("Current balance is \(accountBalance)")}
}

class SavingsAccount: BankAccount {
var interestRate: Float = 0.0

init(number: Int, balance: Float, rate: Float)
{
interestRate = rate
super.init(number: number, balance: balance)
}

func calculateInterest() -> Float{return interestRate * accountBalance}
override func displayBalance(){
super.displayBalance()
print("Prevailing interest rate is \(interestRate)")
}
}

var x = SavingsAccount(number: 12311, balance: 600.00, rate: 0.07)
x.interestRate = 5
x.displayBalance()

**********************************************************************************
add jutsu to any class :

extension ClassName {
// new features here
}

usage :

import Foundation
// inheritance with override
extension Double {
var squared: Double {
return self * self}
var cubed: Double {
return self * self * self}
}

// usage :

let myValue: Double = 3.0
print(myValue.squared)

***********************************************************
array :
var treeArray = ["Pine", "Oak", "Yew"]
var treeArray: [String] = ["Pine", "Oak", "Yew"]
var variableName = [type]() // empty array
var nameArray = [String](repeating: "My String", count: 10) // a 10 sized array
// with each organ containing "My String"

let firstArray = ["Red", "Green", "Blue"]
let secondArray = ["Indigo", "Violet"]
// monster fusion spell card :
let thirdArray = firstArray + secondArray

get array count : arrayVar.count
is array empty Bool : .isEmpty
get specific organ in the array : arrayVar[2]
set organ : arrayVar[1] = "Redwood"

********************************************

append to array :

var treeArray = ["Pine", "Oak", "Yew"]
treeArray.append("Redwood")
treeArray += ["Redwood"]
treeArray += ["Redwood", "Maple", "Birch"]
print(treeArray) // output : ["Pine", "Oak", "Yew", "Redwood", "Redwood", "Redwood", "Maple", "Birch"]

array tricks : treeArray.insert("Maple", at: 0)
treeArray.remove(at: 2)
treeArray.removeLast()

array loop (object loop):

let treeArray = ["Pine", "Oak", "Yew", "Maple", "Birch", "Myrtle"]
for tree in treeArray {print(tree)}

**********************************************************
mixed object array :

let mixedArray: [Any] = [1, 2, 45, "Hello"]

**********************************************************

var casting and Any type var :

let x :Any?
x = 10
var y = x as! Int
print(y + 1)

*****************************************************************************

Dictionary type var :
var bookDict = ["battle programming grimoire": "30$",
"xamarin grimoire" : "20$", "android gromoire" : "25$"]
print(bookDict)

OR :

// declare using type annotation :
var bookDict: [String: String] = ["battle programming grimoire": "30$",
"xamarin grimoire" : "20$", "android gromoire" : "25$"]
print(bookDict)

OR :

var myDictionary = [Int: String]() // declare an empty dictionary

*************************************************************************8

Sequence - based Dictionary Initialization

let keys = ["battle programming grimoire","book2","book3"]
let values = [30,20,25]
let bookDict = Dictionary(uniqueKeysWithValues: zip(keys, values))
print(bookDict)//output :
// ["book2": 20, "book3": 25, "battle programming grimoire": 30]

the above zip can use ranges :

let keys = ["battle programming grimoire","book2","book3"]
let bookDict = Dictionary(uniqueKeysWithValues: zip(keys, 1...))
print(bookDict)//output :
// ["book3": 3, "battle programming grimoire": 1, "book2": 2]

bookDict.count // gets size of dictionary
bookDict[key] // get organ
print(bookDict["hadouken", default: 9001]) // get organ of default val if not found

set dictionary organ val :
bookDict["200-532874"] = "Sense and Sensibility"

OR :
bookDict.updateValue("The Ruins", forKey: "200-532874")

add or remove a dictionary organ :

import Foundation

let keys = ["battle programming grimoire","book2","book3"]
var bookDict = Dictionary(uniqueKeysWithValues: zip(keys, 1...))
bookDict["300-898871"] = 4 // add a key
print(bookDict)
bookDict.removeValue(forKey: "300-898871")
print(bookDict)

dictionary iteration :

for (bookid, title) in bookDict {
print("Book ID: \(bookid) Title: \(title)")}

***************************************************************************
err handling :

Code:

// some global vars :
let connectionOK = true
let connectionSpeed = 31.00
let fileFound = true

// an enum of errs
enum FileTransferError: Error {
case noConnection
case lowBandwidth
case fileNotFound
}
// a fuction that may throw an err
func fileTransfer() throws -> Bool{
    guard connectionOK else {throw FileTransferError.noConnection}
    guard connectionSpeed > 30 else {throw FileTransferError.lowBandwidth}
    guard fileFound else {throw FileTransferError.fileNotFound}
    return true
}

// using a throuse func
func sendFile() -> String {
do {try fileTransfer()} catch FileTransferError.noConnection {return("No Network Connection")}
 catch FileTransferError.lowBandwidth {return("File Transfer Speed too Low")}
 catch FileTransferError.fileNotFound {return("File not Found")}
 catch {return("Unknown error")}
return("Successful transfer")}

print(sendFile())


Code:

if you know an err wont arise :
func sendFile() -> String {
try! fileTransfer() // you know it won't cause an error but the
//func you're using has throws in the signature

defer :

func sendFile() -> String {
    defer {print("code to run right before return")}
try! fileTransfer() // you know it won't cause an error but the func you're using has throws in the signature
return("Successful transfer")}
print(sendFile())
// output :
// code to run right before return
// Successful transfer


hadouken :tokushushoukan

descriptionios app dev Emptyios playing with textbox

more_horiz
ios app dev 2mfcik

Start Xcode, select Create  a  new  Xcode  project, Single  ViewApp template,
change the Language menu to Swift.

Main.storyboard is the UserInterface, widgts from the object library panel.
to set the widghts attributes use the  Attributes Inspector panel  (View
->  Utilities -> Show Attributes Inspector)

view all layout outlines :Editor -> Canvas -> Show Bounds Rectangles

add Auto Layout constraint to make to app compatible with many devices :
click the |-triangle-| in the lower toolbar
all views in controller, select the Reset to Suggested Constraints.

with the main.storyboard file selected, display the Assistant Editor by selecting the View->
Assistant Editor -> show Assistant Editor menu option.
OR click the button with the 2 interlocking circles(the center btn)
IF more assistant editor panels are needed, use the view, Assistant editor, add Assistant
Editor menu option.
if the editor is displaying the wrong file, change it from its upper toolbar.

ctrl click drag the widgt to the code line immediately beneath the class declaration
(in ViewController.swift).
a little outlet window pops up, choose a name for it.

to add an action do the same but cnrl drag drop beneath  the existing viewDidLoad method,
set the event to touch up inside


Code:

//
//  ViewController.swift
//  helloworld
//
//  Created by moti barski on 23.10.2018.
//  Copyright  2018 moti barski. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    // ctrl drag drop widget here to get its input (use interlocking circles btn to get main.story + this screen)
    @IBOutlet weak var txtTemp: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func textFieldReturn(_ sender: UITextField) {
        /* hide keyboard when return key is touched
        to add : ctrl drag drop below viewdid load
        type : UITextField, event : Did End on Exit
        */
        _ = sender.resignFirstResponder()
    }
    @IBAction func klik(_ sender: Any) {
        // ctrl drag drop widget here to get widgt event methode (use interlocking circles btn to get main.story + this screen)
        guard let tempString = txtTemp.text else{return}
        if let fahrenheit = float_t(tempString){
            let celcius = (fahrenheit - 32)/1.8
            let resultText = "Celcius\(celcius)"
            txtTemp.text = resultText
        }
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // hide keyboard
        txtTemp.endEditing(true)
    }
}


(you can drag additional btns to the same action code that was generated) :
set each widgt tag attribut to a dif number (0 to 1000)
change sender: Any to UIButton
and use :
switch sender.tag
to see which button was clicked

descriptionios app dev Emptyget a control placement hierarchy

more_horiz
ios app dev 2mvmt8

to get a control placement hierarchy ctrl+shift click or hard touch pad click it.
and see on which UIview it is placed :

The Window : the platform view that contains all views

descriptionios app dev Emptyios layout constraints

more_horiz
ios app dev 2mvmy5



layout constraints or multi widgt container in interface builder :

create a new Xcode project, single view app template.

select an added widgt,
at the bottom toolbar you have 4 constraint adding tools. uncheck the constraint to margin 1st.

upon pressing the play button (top left) you can :
command + <-,-> to flip the emulator.

constraint between 2 widgts : ctrl + drag widgt A to B, select visual relation,
click the refresh button at the buttom toolbar


cmd + option + 4 = get widget attributes

descriptionios app dev Emptyios label widgt key changed event

more_horiz
ios app dev 2mvn2m


label action view :
uppon ctrl + drag dropping the label in to the code, in the pop up menu :
set the connection to action, type UITextField, (event : editing changed)
🤡

descriptionios app dev Emptyios alert dialogs

more_horiz
ios app dev 2n1vtf

add a segmented control widget to the view, from its properties set it with 5
segments: first to 5th.

////////////////////////////////////////////////////////////
//if you accidentely deleted a view use cmd + z to undo it//
////////////////////////////////////////////////////////////


drag drop the segment action, set the sender to Any.

add a View widgt. on it a viewImage and btn widgts.
drag drop a picture to Assets.xcassets under Appicon, and set the imageview image
pro[erty to sssaid image.

drag drop an outlet to the added view and name it : classicView

Code:


//
//  ViewController.swift
//  segment
//
//  Created by moti barski on 20.11.2018.
//  Copyright  2018 moti barski. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var classicView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func sqmtAlert(_ sender: Any) {
        // tell the sender to behave as a UISegmentedControl
        switch (sender as! UISegmentedControl).selectedSegmentIndex{
        case 0:
            print("ochitsuite")
            closeAll()
        case 1:
            classicAlert()
        case 2:
            simpleDialog()
        case 3://
            complexDialog()
        case 4://
            complexDialogConfig()
        default :
        print("mondai")
    }
    
}
    fileprivate func closeAll()
    {
        classicView.isHidden=true
    }
    fileprivate func classicAlert(){
        classicView.isHidden=false
    }
    fileprivate func simpleDialog(){
        let alert = UIAlertController(title: "simple alert", message: "hadoken", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "x", style: .default, handler:nil))
        alert.addAction(UIAlertAction(title: "y", style: .default, handler:nil))
        alert.addAction(UIAlertAction(title: "cancel", style: .cancel, handler:nil))
        show(alert,sender: nil)
    }
    fileprivate func complexDialog(){
        // an alert with a txt boxe
        let alert = UIAlertController(title: "pass needed", message: "enter pass", preferredStyle: .alert)
        // add text field :
        alert.addTextField(configurationHandler: nil)
        alert.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "login", style: .default, handler: {
            (action) in
            let fields=alert.textFields!
            let txtField=fields[0].text!
            if(txtField=="password1"){self.classicView.isHidden=false}
            //show the dialog :
        }))
        present(alert, animated: true, completion:nil)
    }
    fileprivate func complexDialogConfig(){
        // an alert with twicked txt boxes
        let alert=UIAlertController(title: "mb rulz", message: "mock hack", preferredStyle: .alert)
        var uName,uPass :UITextField!
        // create text field :
        alert.addTextField(configurationHandler: {
            (userName) in
            userName.placeholder = "Enter your name...."
            uName=userName
        })
        alert.addTextField(configurationHandler: {
            (userPass) in
            userPass.placeholder = "Enter your password..."
            userPass.isSecureTextEntry=true
            uPass=userPass
        })
        func okHandler(action:UIAlertAction){
            // closur type function
            if (uName.text=="moti" && uPass.text=="1234")
            {
                self.classicView.isHidden=false
            }}
        
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: {
            (action) in
            print ("you don't want motti gallry?? we have Gina there")
        }))
        
        alert.addAction(UIAlertAction(title: "Hack", style: .default, handler: okHandler))
        
        
        //show the startup
        present(alert, animated: true, completion: nil)
    }
    
    @IBAction func closeAlert(_ sender: UIButton) {
        // closes the views visibility
        classicView.isHidden=true
    }
    
    
}


hadouken :tu:

descriptionios app dev EmptyRe: ios app dev

more_horiz
ios app dev 2nfyrl



add a txt widget : set 3 constraints : up, left, right : all 24
add a btn constraint under the txt box (centered)
add a label constraint under the btn (centered)

ViewController.swift code :

Code:

//
//  ViewController.swift
//  helloWorld
//
//  Created by moti barski on 26.11.2018.
//  Copyright ©️ 2018 moti barski. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var txtBox1: UITextField!
    
    
    @IBOutlet weak var lblOne: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func engaged(_ sender: Any) {
        if let text = txtBox1.text, !text.isEmpty{
            lblOne.text = "hello " + text
        }
        else{lblOne.text = nil}
        
    }
    
}



hadouken :tu:

descriptionios app dev Emptyios 12 widgt container

more_horiz
ios app dev 2nkwa5



widgt container examplified for the 4 calculator btns :

widgts :
2 txt, 4 btn(+-x\), lbl

select all buttons and click the embed in button at the buttom of the story board
to put them all in a stack view container

set the container attributes :
alignment fill, fill equaly, spacing (12)

proTIP : you can drag drop outlets from story board solution explorer instead from the activity form (the actual widgt):

proTIP : cmd+shift+o : type tab to set active -> go to viewcontroller

proTIP : you can delete a widgt constraint : click widgt active,
choose the rooler icon AKA size inspector (at the top right of the screen(or cmd alt 4)),
select and back space a constraint

proTIP : from the add new constraint button in the story board you can set the widgt height and width

drag drop btn action, drag drop the other button actions into the same action code block you just created(4 D 1st btn)

write some code :

Code:


//
//  ViewController.swift
//  calculator
//
//  Created by moti barski on 27.11.2018.
//  Copyright  2018 moti barski. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var txt1: UITextField!
    
    @IBOutlet weak var txt2: UITextField!
    @IBOutlet weak var lbl1: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func engaged(_ sender: UIButton) {
        guard let str1 = txt1.text, let n1 = Int(str1) else{
            lbl1.text = "invalid something"
            return
        }
        guard let str2 = txt2.text, let n2 = Int(str2) else{
            lbl1.text = "invalid something"
            return
        }
        var result : Int
        result = 1
        switch sender.tag {
        case 0:
            result = n1 + n2
        case 1:
            result = n1 - n2
        case 2:
            result = n1 * n2
        case 3:
            result = n1 / n2
        default:
            lbl1.text = "some err"
        }
        lbl1.text = "\(result)"
    }
    
}


hadouken :nice:

descriptionios app dev EmptyRe: ios app dev

more_horiz
ios app dev 2o0h62

add txtBox, label

add to the code lbl outlet, txt action (event = editing changed),
type = UITextField

code :

Code:


//
//  ViewController.swift
//  arraysum
//
//  Created by moti barski on 03/12/2018.
//  Copyright  2018 moti barski. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var lbl1: UILabel!
    
    @IBAction func engaged(_ sender: UITextField) {
        // sum all nums separated by '
        //ignore all none numbers :
        guard let text = sender.text else{
            lbl1.text = ""
            return
        }
        let arr : [String] = text.components(separatedBy:",")
        var sum = 0
        for obj in arr{
            guard let num = Int(obj) else{continue}
            sum += num
        }
        lbl1.text = String(sum)
        // or replace all this methode code with the below code line :
        //lbl1.text = "\((sender.text ?? "").components(separatedBy: ",").reduce(0) { $0 + (Int($1) ?? 0)})"
    }
    

}


hadouken
:greatscott:

descriptionios app dev Emptyios 12 change view color

more_horiz
ios app dev 2oisjf


UI :
btn red, btnblue : both in stack view
UIView

outlet UIview
outlet : btnBlue, btnRed

btnBlue action, set type to UIButton
btnRed drag drop into btnBlue action

code :

Code:

//
//  ViewController.swift
//  changeViewColor
//
//  Created by moti barski on 05/12/2018.
//  Copyright  2018 moti barski. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myView: UIView!
   
    @IBOutlet weak var btnBlue: UIButton!
   
    @IBOutlet weak var btnRed: UIButton!
   
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func colorJutsu(_ sender: UIButton) {
        switch sender{
        case btnBlue:
            myView.backgroundColor = UIColor.blue
        case btnRed:
            myView.backgroundColor = .red
        default:
            break
        }
       
    }
   
}


hadouken :8@:



Last edited by Moti Barski on Sun Dec 09, 2018 5:32 am; edited 1 time in total

descriptionios app dev Emptyios12 creat and use an extention for an existing class

more_horiz
ios app dev 2olnc5

creating an extention to an existing class :
the color class in this example



add swift file : cmd + n
call it Utils

code Utils.swift:

Code:


//
//  Utils.swift
//  changeViewColor
//
//  Created by moti barski on 10/12/2018.
//  Copyright  2018 moti barski. All rights reserved.
//

import UIKit

extension UIColor{
    // extends the existing UIColor
    class var random : UIColor{
        get{
            // returns a random color
            let randRed = CGFloat(arc4random_uniform(256))
            let randBlue = CGFloat(arc4random_uniform(256))
            let randGreen = CGFloat(arc4random_uniform(256))
            return UIColor(red: randRed / 255, green: randGreen / 255, blue: randBlue / 255, alpha: 1)
        }
    }
}


using the extention :



add btnRnd + outlet + action

code (main):

Code:


//
//  ViewController.swift
//  changeViewColor
//
//  Created by moti barski on 05/12/2018.
//  Copyright  2018 moti barski. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myView: UIView!
    
    @IBOutlet weak var btnBlue: UIButton!
    
    @IBOutlet weak var btnRed: UIButton!
    
    @IBOutlet weak var btnRnd: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func colorJutsu(_ sender: UIButton) {
        
        func change(to color : UIColor){
            // local function
            UIView.animate(withDuration: 0.7){self.myView.backgroundColor = color}
        }
        switch sender{
        case btnBlue:
            change(to: UIColor.blue)
        case btnRed:
            http://myView.backgroundColor = .red
            change(to: .red)
        case btnRnd:
        // using the extention I made earlier :
            change(to: .random)
        default:
            break
        }
        
    }
    
}




note the code also uses a local func to make a simple
transition animation

descriptionios app dev Emptytransfer data between 2 view controllers

more_horiz
ios app dev 2p0jul



activity A :
txtbox, place holder : type something
btn, text : go to B

add view controller (this is the activity B)
lbl : I am B
txtbox
btn, text : back

control drag btn of activity A to activity B. a segwae is created
, choose present modely. this button will teleport from A to B

the activity segwae has some transition atributes to play with

create code for activity B :
cmd + N, cocoa touch class :
class : SecondViewController
subclass of UIViewController
uncheck xib

set a class for the 2nd activity :
on the storyboard click its yellow btn, identity inspector
(on the right solution explorer). class : SecondViewController

add back action to the btn(of activity B) event : Touch Up Inside
this will kill activity B and go back to activity A

add the respective text fields outlets per activity



make the keyboard disapperar after return button pressed at text box :
activity A add action to txtbox : didEndOnExit (return key pressed)
textbox.resignFirstResponder()

code activity A :

Code:

//
//  ViewController.swift
//  two_activities
//
//  Created by moti barski on 14/12/2018.
//  Copyright  2018 moti barski. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var txtA: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    @IBAction func keyboardLess(_ sender: Any) {
        // kill keyboard
        txtA.resignFirstResponder()
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let secondVC = segue.destination as? SecondViewController{secondVC.textForTextField = txtA.text}
    }

}


code activity B :

Code:

//
//  SecondViewController.swift
//  two_activities
//
//  Created by moti barski on 14/12/2018.
//  Copyright  2018 moti barski. All rights reserved.
//

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var txtB: UITextField!
    var textForTextField : String?
    override func viewDidLoad() {
        super.viewDidLoad()
        txtB.text = textForTextField
        // Do any additional setup after loading the view.
    }
    
    @IBAction func backAction(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}


protip : debug : type po varname to watch var, after creating a break point by clicking at the left of a code line

Last edited by Moti Barski on Sat Dec 15, 2018 1:34 am; edited 1 time in total

descriptionios app dev Emptyusing delegate to get data from a dead activity

more_horiz
ios app dev 2pezkr

activity A :
text box
button + segue to activity B

activity B :

text box
button

link activity B to cocoa class (see prev walkthrough of adding activities)

code activity B :

Code:


//
//  Activity2.swift
//  region
//
//  Created by moti barski on 20/12/2018.
//  Copyright  2018 moti barski. All rights reserved.
//

import UIKit

protocol SecondViewControllerDelegate{
    // this is like an interfac
    func secondVC(_ controller : Activity2, didFinishWith text: String?)
}

class Activity2: UIViewController {

    @IBOutlet weak var txt2: UITextField!
    var delegate : SecondViewControllerDelegate?
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
   
    @IBAction func backAction(_ sender: Any) {
        delegate?.secondVC(self, didFinishWith: txt2.text)
        // go back and kill this activity :
        self.dismiss(animated: true, completion: nil)
    }
}


code activity A :

Code:


import UIKit

class ViewController: UIViewController, SecondViewControllerDelegate {

    @IBOutlet weak var txt1: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
   
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let secondVC = segue.destination as? Activity2{
            secondVC.delegate = self
        }
    }
    // special comment for quick navigation :
    //MARK - 2nd view controller delegate methode -
    func secondVC(_ controller: Activity2, didFinishWith text: String?) {
        self.txt1.text = text
    }
}


hadouken :clr:

descriptionios app dev Emptyios12 radio player

more_horiz
plays online mp3

ios app dev 2ppdeu

I used : for the file
radiosure.com

download and install icons8 mac app from icons8.com
this makes getting icons for apps easyer.

protip : cmd + tab or cmd + shift + tab: switch between active apps

drag drop icons into the assets folder from the icons8 app or with a png file
size 25 recommended :
play,pause, mute, max volume



btn placed center on the view :
control drag said btn to the main activity, center horizentaly + center verticaly,
cmd + option + =
this will unerror it and place it centered on the main UIView
or auto fix (the option should pop up)

btn attributes :
set image to an icon you added
state config : selected // this enables you to set an image for the selected or unselected of the btn (toggle)
and choose an image for that state as well (by checking the selected chkbox)

slider

atttributes : min max image

btn : toggle named action

slider : outlet, + action : volume action
sender : UISlider

ViewController.swift code :

Code:


import UIKit
import AVFoundation

class ViewController: UIViewController {

    @IBOutlet weak var slider: UISlider!
    var urlString = "http://glzwizzlv.bynetcdn.com/glz_mp3"
    var player : AVPlayer?
   
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func toggle(_ sender: UIButton) {
        if player == nil{
            // start playing
            let url = URL(string: urlString)
            player = AVPlayer(url: url!)
            player?.volume = slider.value
            player?.play()
            sender.isSelected = true
        }else{
            // stop playing
            sender.isSelected = false
            player?.pause()
            player = nil
        }
       
    }
   
    @IBAction func volumeAction(_ sender: UISlider) {
        player?.volume = sender.value
    }
}


info.plist
right click the empty area, add row,
App transport security settings, drop down arrow,
+, allow arbitrary loads, change no to yes

descriptionios app dev Emptyios12 add a view programatically

more_horiz

ios app dev 2q1k7d

protip : in a view widgt setting the property clip to bounds
will make any nested widgts not exide the views borders.

add cocoa class : cmd + n :
subclass of UIView
name : BorderBlueView

BorderBlueView.swift :

Code:


import UIKit

class BorderBlueView: UIView {

    //from story board :
    required init?(coder aDecoder: NSCoder){
        super.init(coder: aDecoder)
        setup()
    }
    //from code :
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    private func setup(){
        self.backgroundColor = UIColor.blue
        self.layer.borderWidth = 2
        self.layer.borderColor = UIColor.red.cgColor
        self.layer.cornerRadius = 16
    }
 
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}


ViewController.swift :

Code:


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        createView()
    }
    private func createView(){
        let rect = CGRect(x: 50, y: 50, width: 120, height: 120)
        let myView = BorderBlueView(frame: rect)
        self.view.addSubview(myView)
    }

}



adding : @IBDesignable like so :

@IBDesignable class BorderBlueView: UIView {

makes the storyboard show the class effects before compiling
assuming you attach the cocoa class to a view you added
(set the view class to BorderBlueView at the identity inspector)

descriptionios app dev Emptyios12 simple save load data no jutsu

more_horiz
ios app dev 2qq70f



Code:

fileprivate func saveSomeData()
    {
        //declare of userDefaults (android: shared preferences)
        let defaults = UserDefaults.standard
       
        //let write an integer
        defaults.set(25,forKey:"Age")
       
        //let write some boolean
        defaults.set(true, forKey: "userLoggedIn")
       
        //let write some CG data
        defaults.set(CGFloat.pi, forKey: "Pi")
       
        //let write some String
        defaults.set("Arial the prince",forKey: "WhoIsYourMan")
       
        //let write some Date
        defaults.set(Date(), forKey:"LastRun")
       
        //let write some array
        let array = ["Arial","Michael","Leonid"]
        defaults.set(array, forKey:"savedArray")
       
        //let write some dictinaries
        let dict=["Name" : "James Bond","Country":"UK"]
        defaults.set(dict, forKey:"savedDict")

       
        //what about reading ?!
        let age = defaults.integer(forKey: "Age")
        let userLogged = defaults.bool(forKey: "userLoggedIn")
        let pi = defaults.double(forKey: "Pi")
       
        //array
        let savedArray = defaults.object(forKey: "savedArray") as? [String] ?? [String]()
       
        let Evgniy = defaults.dictionary(forKey: "savedDict")
       
    }


hadouken :tu:

descriptionios app dev Emptyios play sound and animate a view

more_horiz


shoryuken app :

ios app dev 2s7obf

shoryuken (png) to asset folder
(shoryuken) wav file to the project folder

protip: cmd space, type digital color meter : get color by hovering over it
set main view background to it

protip : cmd E : replicate view

cmd + shift + L, open choose widgt(View) to add an image view from the object library
set the image to kens png


code for playing sound files and simple view animation :

Code:



import UIKit
import AVFoundation

class ViewController: UIViewController {
    var player: AVAudioPlayer!

    @IBOutlet weak var img1: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let path = Bundle.main.path(forResource: "fighter", ofType: "mp3")!
        let url = URL(fileURLWithPath: path)
        do{
            player = try AVAudioPlayer(contentsOf: url)
            player.prepareToPlay()}
        catch let error as NSError{print(error.description)}
        player.play()
        // animation for the image :
        UIView.animate(withDuration: 2.3, animations: {self.img1.frame = CGRect(x: 0, y: 20, width: 375, height: 402)})
    }


}

shoryuken ☀

descriptionios app dev Emptyswift terner operator

more_horiz
AKA shortened if :

Code:

var x = 10 > 5 ? "hadouken" : "shouryuken"
print(x) // prints hadouken


pickle rick!

descriptionios app dev Emptystrings and noob Justus

more_horiz

Code:

import UIKit

//strings
var name: String = "ryu"
var attack = "hadouken" // swift recomends declering like this (type inference)
var line = "\(name) \(attack)" // string interpolation
line.append(" shouryuken")
line = line.capitalized
var line2:String = line.lowercased()
line2 = line.replacingOccurrences(of: "Hadouken", with: "katon gouka mekyaku")
print(line2)
// protip : cmd shift enter : shortcut to run playground


rick Sanches !

descriptionios app dev Emptyswift loops

more_horiz

Code:

import UIKit


let cat = "????";print(cat)
var x=0
repeat{print(x);x+=1}while(x<50)
for i in 1...5{print("index \(i)")}
for i in 1..<5{print("index2 \(i)")}
var salaries = [2000,3000,1500]
for salary in salaries{print("salary: \(salary)")}
// protip : cmd shift enter : shortcut to run playground

descriptionios app dev Emptyswift dictionary

more_horiz

Code:

import UIKit

var nameOfNum = [Int:String]() // declared dictionary
nameOfNum[1] = "one";nameOfNum[2] = "two"
print(nameOfNum[1]!)
nameOfNum = [:] // reset clear dictionary
var anime: [String:String] = ["tate no yuusha":"adventure", "DBZ":"fighting"]
print("there are \(anime.count) shows")
if nameOfNum.isEmpty {print("no entries in nums dictionary")}
anime["tate no yuusha"] = nil // clear entry
nameOfNum[1] = "one";nameOfNum[2] = "two"
for (num, literalNum) in nameOfNum{print("\(num):\(literalNum)")}
for key in nameOfNum.keys{print("key: \(key)")}
for value in nameOfNum.values{print("value: \(value)")}

🇵🇷

descriptionios app dev Emptyswift inheritance

more_horiz

Code:

import UIKit

class Vehicle{
    var tires = 4;var make: String?;var model: String?;var currentSpeed: Double = 0
    // c'tor :
    init() {
        print("I am the parent")
    }
    func drive(speedIncrease: Double){
        self.currentSpeed += speedIncrease * 2
    }
    func brake(){
        self.currentSpeed = 0
    }
}

class SportsCar: Vehicle{
    // child class of car parent class
    override init() {
        super.init()
        make = "BMW"
        model = "x series"
        print("I am the child")
    }
    override func drive(speedIncrease: Double) {
        currentSpeed += speedIncrease * 3
    }
}

let car = SportsCar()
car.drive(speedIncrease: 3);print(car.currentSpeed)

:tu:

descriptionios app dev Emptyswift polymorphism

more_horiz

Code:

import UIKit

class Shape{
    var area:Double?
    init() {
        area = 0
    }
    func calcArea(varA: Double,varB: Double){
       
    }
    func getArea()-> Double{return self.area!}
}
class Squar: Shape{
    override func calcArea(varA: Double, varB: Double) {
        self.area = varA * varB
    }
}
class Triangle: Shape{
    override func calcArea(varA: Double, varB: Double) {
        self.area = (varA * varB) / 2
    }
}

var squar = Squar()
squar.calcArea(varA: 2, varB: 3)
var triangle = Triangle()
triangle.calcArea(varA: 2, varB: 3)
print(squar.getArea())
print(triangle.getArea())


🐉 :bmb:

descriptionios app dev Emptyswift optionals

more_horiz

Code:

import UIKit

let optionalImage: UIImage? =  #imageLiteral(resourceName: "angewomonm.jpg")
// editor, insert image literal after = above, run it, click show result at the right window.

var optionalNum : Int? = 5 // may be nil or a number can change 5 to nil (null)
var numba : Int = 5
// force unwrapping
if optionalNum != nil {print("optional number is \(optionalNum)")}else{print("it's a nil")}

// optional binding
var optioNum : Int? = nil
if let constNum = optioNum {print("\(constNum)")}else{print("is nil")}

var optionalN : Int? = 4

func intPrinter(){
guard let constN = optionalN else { return }
print("it is not a nil")
}

intPrinter()

// ipmlicitly unwrapped optionals :

let assumedVal : Int! = 5 // if this is nil you will crash the program
let implicitVal : Int = assumedVal // must be sure assumedVal is not nil

let n1: Int? = nil
let result = n1 ?? 0 // will be 0 ifn1 is nil

// optional chaining
class Theater{
    var admissionBadge: AdmissionPass?
    init(badge: AdmissionPass?){self.admissionBadge = badge}
}

class AdmissionPass {
    var numOfDays: Int
    init(numOfDays: Int){self.numOfDays = numOfDays}
}
let admissionBadge = AdmissionPass(numOfDays: 2)
let atendee = Theater(badge: admissionBadge)
if let daysAttendable = atendee.admissionBadge?.numOfDays {print("can attend \(daysAttendable) days")}
else{print("no pass found")}


Kamehameha :nice:

descriptionios app dev Emptyterminal

more_horiz
ios app dev 2tyqsm

cmd + space, search terminal

commands :
cd Desktop // goes to the desktop dir cd [folder]
ls // list items in the dir
tab key : auto complete commands while typing
cd .. // go one dir back
cd    // go to starter dir

clear // clrscr
mkdir name // create a folder
mv [file] [dir] // cut paste file
touch filename.extention : create file
touch filename.txt // creat a text file
touch filename.txt  index.html // create all sorts of files in one cmd line
mv filename.extention ../ // move file up a dir
mv filename.extention ../[existing dir name] // move file into dir
cp filename.extention foldername //: aftercp filename.extention  you can drag drop the folder
into the terminal
mv filename.extention newfilename.exe // rename

cmd + k // clrscr
rm [file.extention] // remove a file
rm [file.extention] [file2.extention] [filen.extention]// removes files
rmdir [dir] // delete an empty directory
rm -R [dir] // del directory and it's contents

:tu:
privacy_tip Permissions in this forum:
You cannot reply to topics in this forum
power_settings_newLogin to reply