article

Monday, May 17, 2021

SwiftUI Background Color list with alternate colors

SwiftUI Background Color list with alternate colors
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State private var items = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]

    var body: some View {
        List {
            ForEach(items.indices) { index in
                Text(items[index])
                    .listRowBackground((index  % 2 == 0) ? Color(.systemBlue) : Color(.yellow))
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

SwiftUI Fetch JSON data display into list and view details to another view

SwiftUI Fetch JSON data display into list and view details to another view


Learn how to create an API call to get data from a remote JSON file and display this data in a SwiftUI list

I used dropbox to host my json file url : https://dl.dropboxusercontent.com/s/1y7yqdefyayegzo/employeelist.json?dl=0
ContentView.swift
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct User: Decodable {
    let id: String
    let name: String
    let email: String
    let about: String
}

struct ContentView: View {
    @State var users = [User]()

    var body: some View {
        NavigationView {
            List{
                ForEach(users, id: \.id) { item in
                    NavigationLink(destination: details(item: item)) {
                        HStack {
                            //Image("user")
                                //.resizable()
                                //.frame(width: 50, height: 50)
                                //.clipShape(Circle())
                                //.overlay(Circle().stroke(Color.white, lineWidth: 4))
                            Text(item.name)
                                .font(.headline)
                            //Text(item.email)
                            //Text(item.about)
                        }.padding(7)
                    }
                }
            }
            .onAppear(perform: loadData)
            .navigationTitle("Navigation")
        }
    }

    func loadData() {
        guard let url = URL(string: "https://dl.dropboxusercontent.com/s/1y7yqdefyayegzo/employeelist.json?dl=0") else {
            print("Invalid URL")
            return
        }
        let request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request) {data, response, error in
            if let data = data {
                //pull out the declaration of the decoder object
                let decoder = JSONDecoder()
                //set how we want to interpret dates in the JSON
                decoder.dateDecodingStrategy = .iso8601
                //decode directly to an array of User structs rather than a Response
                if let decodedResponse = try?
                    decoder.decode([User].self, from: data) {
                    DispatchQueue.main.async {
                        //decodedResponse is now [User] rather than Response.User
                        self.users = decodedResponse
                    }
                    return
                }
            }
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")

        }.resume()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
details.swift
 
//
//  details.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct details: View {
    
    let item: User
    
    var body: some View {
        
        VStack {
            Image("user")
                .clipShape(Circle())
                .overlay(
                    Circle().stroke(Color.orange, lineWidth: 4)
                )
                .shadow(radius: 10)
            Text(item.name)
                .font(.title)
            Text(item.email)
                .font(.subheadline)
            
            Divider()
 
            Text(item.about)
                .font(.headline)
                .multilineTextAlignment(.center)
                .lineLimit(50)
        }.padding()
        
    }
}

SwiftUI Lists and Navigation displays a list of SF Simbles

SwiftUI Lists and Navigation displays a list of SF Simbles


simple app that displays a list of SF Simbles, tapping on any of the SF Simbles will let you navigate to a different view showing details
 
//
//  ContentView.swift
//  Devapp
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    private let SFsimbleList: [SFsimbleItem] = [
        SFsimbleItem(
        sfsimble: "photo.tv",
        name: "Photo Tv",
        description: "SF Symbols provides a set of over 1,500 consistent, highly configurable symbols you can use in your app. Apple designed SF Symbols to integrate seamlessly with the San Francisco system font."),
        SFsimbleItem(
        sfsimble: "display.2",
        name: "Display",
        description: "SF Symbols provides a set of over 1,500 consistent, highly configurable symbols you can use in your app. Apple designed SF Symbols to integrate seamlessly with the San Francisco system font."),
        SFsimbleItem(
        sfsimble: "server.rack",
        name: "Server Rack",
        description: "SF Symbols provides a set of over 1,500 consistent, highly configurable symbols you can use in your app. Apple designed SF Symbols to integrate seamlessly with the San Francisco system font."),
        SFsimbleItem(
        sfsimble: "iphone",
        name: "Iphone",
        description: "SF Symbols provides a set of over 1,500 consistent, highly configurable symbols you can use in your app. Apple designed SF Symbols to integrate seamlessly with the San Francisco system font."),
        SFsimbleItem(
        sfsimble: "applewatch",
        name: "Apple watch",
        description: "SF Symbols provides a set of over 1,500 consistent, highly configurable symbols you can use in your app. Apple designed SF Symbols to integrate seamlessly with the San Francisco system font."),
        SFsimbleItem(
        sfsimble: "earpods",
        name: "Earpods",
        description: "SF Symbols provides a set of over 1,500 consistent, highly configurable symbols you can use in your app. Apple designed SF Symbols to integrate seamlessly with the San Francisco system font."),
    ]
    
    var body: some View {

        NavigationView {
            List(SFsimbleList) { SFsimbleItem in
              NavigationLink(destination: DetailsView(SFsimbleItem: SFsimbleItem)) {
                HStack {
                    SFSimbleView(SFsimbleItem: SFsimbleItem)
                    
                    Text(SFsimbleItem.name)
                        .font(.headline)
                }.padding(7)
              }
            }
            .navigationBarTitle("SF Symbols in SwiftUI")
        }
    }
}

struct DetailsView: View {

  let SFsimbleItem: SFsimbleItem
  
  var body: some View {
    VStack(alignment: .leading) {
      HStack {
        SFSimbleView(SFsimbleItem: SFsimbleItem)
          .padding(.trailing, 5)
        
        Text(SFsimbleItem.name)
          .font(.largeTitle)
          .bold()
        
        Spacer()
      }
      
      Text(SFsimbleItem.description)
        .padding(.top)
      
      Spacer()
    }
    .padding()
    .navigationBarTitle(Text(SFsimbleItem.name), displayMode: .inline)
  }
}

struct SFSimbleView: View {
  let SFsimbleItem: SFsimbleItem
  
  var body: some View {
    ZStack {
        Image(systemName: SFsimbleItem.sfsimble).foregroundColor(.red)
            .font(.system(size: 40))
            .shadow(radius: 3)
    }
  }
}

struct SFsimbleItem: Identifiable {
  let id = UUID()
  let sfsimble: String
  let name: String
  let description: String
}

struct details_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Thursday, May 13, 2021

Dynamic Select Box using Python Flask PostgreSQL Flask-WTF, javascript and SQLAlchemy

Dynamic Select Box using Python Flask PostgreSQL Flask-WTF, javascript and SQLAlchemy

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2


CREATE TABLE countries (
id serial PRIMARY KEY,
name VARCHAR ( 60 ) NOT NULL
);

INSERT INTO
    countries(id,name)
VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra');

CREATE TABLE state (
id serial PRIMARY KEY,
name VARCHAR ( 60 ) NOT NULL,
country_id INT NOT NULL
);

INSERT INTO state (id, name, country_id) VALUES (1, 'ARMM', 171);
INSERT INTO state (id, name, country_id) VALUES (2, 'Bicol', 171);
INSERT INTO state (id, name, country_id) VALUES (3, 'Central Luzon', 171);
INSERT INTO state (id, name, country_id) VALUES (4, 'Central Mindanao', 171);
INSERT INTO state (id, name, country_id) VALUES (5, 'Alabama', 227);
INSERT INTO state (id, name, country_id) VALUES (6, 'Alaska', 227);
INSERT INTO state (id, name, country_id) VALUES (7, 'Arizona', 227);
INSERT INTO state (id, name, country_id) VALUES (8, 'California', 227);
INSERT INTO state (id, name, country_id) VALUES (9, 'Florida', 227);

CREATE TABLE city (
id serial PRIMARY KEY,
state VARCHAR ( 60 ) NOT NULL,
name VARCHAR ( 60 ) NOT NULL,
stateid INT NOT NULL
);

INSERT INTO city (id, state, name, stateid) VALUES (1, 'CA', 'Anaheim', 8);
INSERT INTO city (id, state, name, stateid) VALUES (2, 'NV', 'Arden-Arcade', 8);
INSERT INTO city (id, state, name, stateid) VALUES (3, 'CA', 'Bakersfield', 8);
INSERT INTO city (id, state, name, stateid) VALUES (4, 'CA', 'Carson', 8);
INSERT INTO city (id, state, name, stateid) VALUES (5, 'NV', 'Daly City', 8);
INSERT INTO city (id, state, name, stateid) VALUES (6, 'AC', 'Angeles City', 3);
INSERT INTO city (id, state, name, stateid) VALUES (7, 'OC', 'Olongapo', 3);
INSERT INTO city (id, state, name, stateid) VALUES (8, 'SF', 'San Fernando', 3);
INSERT INTO city (id, state, name, stateid) VALUES (9, 'TA', 'Tarlac', 3);
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy  
from wtforms import SelectField
from flask_wtf import FlaskForm #https://flask-wtf.readthedocs.io/en/stable/

app = Flask(__name__)

app.config['SECRET_KEY'] = 'cairocoders-ednalan'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
                                                      #password:admin
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:admin@localhost/sampledb' #install psycopg2 https://pypi.org/project/psycopg2/

db = SQLAlchemy(app)

class Country(db.Model):
    __tablename__ = 'countries'
  
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
  
class State(db.Model):
    __tablename__ = 'state'
  
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
    country_id = db.Column(db.Integer)
  
class City(db.Model):
    __tablename__ = 'city'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60))
    stateid = db.Column(db.Integer) 
 
class Form(FlaskForm):
    country = SelectField('country', choices=[])
    state = SelectField('state', choices=[])
    city = SelectField('city', choices=[])
         
@app.route('/', methods=['GET', 'POST'])
def index():
    form = Form()
    form.country.choices = [(country.id, country.name) for country in Country.query.all()]
  
    if request.method == 'POST':
        city = City.query.filter_by(id=form.city.data).first()
        country = Country.query.filter_by(id=form.country.data).first()
        state = State.query.filter_by(id=form.state.data).first()
        return '

Country : {}, State: {}, City: {}

'.format(country.name, state.name, city.name) return render_template('index.html', form=form) @app.route('/state/') def statebycountry(get_state): state = State.query.filter_by(country_id=get_state).all() stateArray = [] for city in state: stateObj = {} stateObj['id'] = city.id stateObj['name'] = city.name stateArray.append(stateObj) return jsonify({'statecountry' : stateArray}) @app.route('/city/') def city(get_city): state_data = City.query.filter_by(stateid=get_city).all() cityArray = [] for city in state_data: cityObj = {} cityObj['id'] = city.id cityObj['name'] = city.name cityArray.append(cityObj) return jsonify({'citylist' : cityArray}) if __name__ == '__main__': app.run(debug=True)
templates/index.html
#templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dynamic Select Box using Python Flask PostgreSQL Flask-WTF, javascript and SQLAlchemy</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-12">
        <p><h2>Dynamic Select Box using Python Flask PostgreSQL Flask-WTF, javascript and SQLAlchemy</h2></p>
        <form method="POST">
          {{ form.csrf_token}}  
                <div class="form-group">
                <label for="email">Country:</label>
                {{ form.country(class="form-control") }}
            </div>
            <div class="form-group">
                <label for="email">State:</label>
                {{ form.state(class="form-control")}}
            </div>
            <div class="form-group">
                <label for="email">City:</label>
                {{ form.city(class="form-control")}} 
            </div>
                <input type="submit" class="btn btn-success" btn-lg>
        </form> 
        </div>
    </div>
</div> 
<script>
country_select = document.getElementById('country');
state_select = document.getElementById('state');
city_select = document.getElementById('city');
 
country_select.onchange = function(){
    country = country_select.value;
    fetch('state/' + country).then(function(response){
        response.json().then(function(data) {
            optionHTML = '';
            for (state of data.statecountry) {
                optionHTML += '<option value="' + state.id +'">' + state.name + '</option>'
            }
            state_select.innerHTML = optionHTML;
        });
    });
}
state_select.onchange = function(){
    city = state_select.value; 
    fetch('city/' + city).then(function(response){
        response.json().then(function(data) {
            optionHTML = '';
            for (city_rs of data.citylist) {
                optionHTML += '<option value="' + city_rs.id +'">' + city_rs.name + '</option>'
            }
            city_select.innerHTML = optionHTML;
        });
    });
}
</script>
</body>
</html>

Wednesday, May 12, 2021

Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database

Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE countries (
id serial PRIMARY KEY,
name VARCHAR ( 60 ) NOT NULL
);

INSERT INTO
    countries(id,name)
VALUES
(1, 'Afghanistan'),
(2, 'Aringland Islands'),
(3, 'Albania'),
(4, 'Algeria'),
(5, 'American Samoa'),
(6, 'Andorra'),
(7, 'Angola'),
(8, 'Anguilla'),
(9, 'Antarctica'),
(10, 'Antigua and Barbuda'),
(11, 'Argentina'),
(12, 'Armenia'),
(13, 'Aruba'),
(14, 'Australia');
app.py
 
#app.py
from flask import Flask, render_template, request, jsonify
from wtforms import StringField, TextField, Form
from wtforms.validators import DataRequired, Length
from flask_sqlalchemy import SQLAlchemy  
 
app = Flask(__name__)

app.config['SECRET_KEY'] = 'cairocoders-ednalan'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
                                                      #password:admin
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:admin@localhost/sampledb'

db = SQLAlchemy(app) 
  
class SearchForm(Form): #create form
    country = StringField('Country', validators=[DataRequired(),Length(max=40)],render_kw={"placeholder": "country"})
 
class Country(db.Model):
    __tablename__='countries'
    id=db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(60), unique=True, nullable = False)
 
    def as_dict(self):
        return {'name': self.name}
   
@app.route('/')
def index():
    form = SearchForm(request.form)
    return render_template('index.html', form=form)
 
@app.route('/countries')
def countrydic():
    res = Country.query.all()

    list_countries = [r.as_dict() for r in res]
    return jsonify(list_countries)
  
@app.route('/process', methods=['POST'])
def process():
    country = request.form['country']
    if country:
        return jsonify({'country':country})
    return jsonify({'error': 'missing data..'})

if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>
<head>
<meta charset="utf-8">
<title>Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
    <h1>Autocomplete Jquery Ajax Using Python Flask PostgreSQL and SQLAlchemy database</h1>
    <form class="form-inline">
    <div class="form-group">
        {{form.country(class="form-control")}}
    </div>
    <button type="submit" class="btn btn-info">Submit</button>
    </form>
    <div id="result"></div>
<script>
$(document).ready(function(){
    var countries=[];
    function loadCountries(){
        $.getJSON('/countries', function(data, status, xhr){
            for (var i = 0; i < data.length; i++ ) {
                countries.push(data[i].name);
            }
        });
    };
    loadCountries();
 
    $('#country').autocomplete({
        source: countries, 
    }); 
 
    $('form').on('submit', function(e){
        $.ajax({
        data: {
            country:$('#country').val()
        },
        type: 'POST',
        url : '/process'
        })
        .done(function(data){ 
            if (data.error){
                $('#result').text(data.error).show();
            }
            else {
                $('#result').html(data.country).show()
            }
        })
        e.preventDefault();
    });
}); 
</script>
<style>
.form-control {
    display: block;
    width:300px;
    padding: .375rem .75rem;
    font-size: 1rem;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.btn {padding: .375rem .75rem; margin-top:10px;}
</style>
  </body>
</html>

Python Flask PostgreSQL Delete Multiple records using checkbox with getlist

Python Flask PostgreSQL Delete Multiple records using checkbox with getlist

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

Crate database table
CREATE TABLE students (
id serial PRIMARY KEY,
fname VARCHAR ( 40 ) NOT NULL,
lname VARCHAR ( 40 ) NOT NULL,
email VARCHAR ( 40 ) NOT NULL
profile_pic VARCHAR ( 150 ) NULL
);

SELECT * FROM students 

Multiple insert
INSERT INTO
    students(id,fname,lname,email)
VALUES
    ('Quinn','Flynn'', 'Flynn'@gmail.com'),
    ('Tiger','nizon', 'nizon@gmail.com'),
    ('Airi','sato', 'sato@gmail.com');
app.py
 
#app.py
from flask import Flask, render_template, flash, redirect, url_for, request
import psycopg2 #pip install psycopg2 
import psycopg2.extras
 
app = Flask(__name__)
 
app.secret_key = "cairocoders-ednalan"
 
DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"
 
conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/')
def home():
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
    cursor.execute("SELECT * FROM students")
    rows = cursor.fetchall()
    return render_template('index.html', students=rows)

@app.route('/delete', methods=['GET', 'POST'])
def index():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

    if request.method == 'POST': 
        #test = request.form.getlist('mycheckbox')
        for getid in request.form.getlist('mycheckbox'):
            print(getid)
            cur.execute('DELETE FROM students WHERE id = {0}'.format(getid))
            conn.commit()
        flash('Student Removed Successfully')
        return redirect('/')

if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Python Flask PostgreSQL Delete Multiple records using checkbox with getlist</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="container">
 <div class="row">
        <div class="col-md-12">
        <p><h2>Python Flask PostgreSQL Delete Multiple records using checkbox with getlist</h2></p>
        <div class="table-responsive">
        <form method="POST" action="/delete">        
        <table id="mytable" class="table table-bordred table-striped">
            <thead>
                <th><input type="checkbox" id="checkall" /></th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
                <th width="50">Edit</th>
                <th width="50">Delete</th>
            </thead>
            <tbody>
            {% for rs in students %}
            <tr>
              <td><input type="checkbox" value="{{ rs.id }}" name="mycheckbox" class="checkthis" /></td>
              <td>{{ rs.fname }}</td>
              <td>{{ rs.lname }}</td>
              <td>{{ rs.email }}</td>
              <td><p data-placement="top" data-toggle="tooltip" title="Edit"><button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>
              <td><p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ><span class="glyphicon glyphicon-trash"></span></button></p></td>
            </tr>
            {% endfor %}
            </tbody>
         
      </table><input type="submit" value="Delete All Selected" class="btn btn-primary">  
      <br/>
      <div>
        {% with messages = get_flashed_messages() %}
            {% if messages %}
            {% for message in messages %}
            <div class="alert alert-danger" role="alert">{{ message }}</div>
            {% endfor %}
            {% endif %}
        {% endwith %}
        </div>
        </form>        
            </div>
             
        </div>
 </div>
</div>
<script>
$(document).ready(function(){
$("#mytable #checkall").click(function () {
        if ($("#mytable #checkall").is(':checked')) {
            $("#mytable input[type=checkbox]").each(function () {
                $(this).prop("checked", true);
            });
 
        } else {
            $("#mytable input[type=checkbox]").each(function () {
                $(this).prop("checked", false);
            });
        }
    });
     
    $("[data-toggle=tooltip]").tooltip();
});
</script>  
</body>
</html>

Tuesday, May 11, 2021

Upload File and validate before save to Database using Python Flask PostgreSQL and SQLAlchemy

Upload File and validate before save to Database using Python Flask PostgreSQL and SQLAlchemy

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

Crate database table
CREATE TABLE students (
id serial PRIMARY KEY,
fname VARCHAR ( 40 ) NOT NULL,
lname VARCHAR ( 40 ) NOT NULL,
email VARCHAR ( 40 ) NOT NULL
profile_pic VARCHAR ( 150 ) NULL
);

SELECT * FROM students 
app.py
#app.py
from flask import Flask, render_template, flash, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request

app = Flask(__name__)

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
                                                      #password:admin
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:admin@localhost/sampledb'
 
db=SQLAlchemy(app)

app.config['SECRET_KEY'] = 'cairocoders-ednalan'
 
UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
  
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
  
def allowed_file(filename):
  return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

class Student(db.Model):
  __tablename__='students'
  id=db.Column(db.Integer,primary_key=True)
  fname=db.Column(db.String(40))
  lname=db.Column(db.String(40))
  email=db.Column(db.String(40))
  profile_pic = db.Column(db.String(150))

  def __init__(self,fname,lname,email,profile_pic):
    self.fname=fname
    self.lname=lname
    self.email=email
    self.profile_pic=profile_pic
  
@app.route('/')
def index():
    return render_template('index.html')
 
@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['inputFile']
    fname = request.form['fname']
    lname = request.form['lname']
    filename = secure_filename(file.filename)
  
    if file and allowed_file(file.filename):
       file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  
       newFile = Student(profile_pic=file.filename, fname=fname, lname=lname, email='cairocoders@gmail.com')
       db.session.add(newFile)
       db.session.commit()
       flash('File successfully uploaded ' + file.filename + ' to the database!')
       return redirect('/')
    else:
       flash('Invalid Uplaod only txt, pdf, png, jpg, jpeg, gif') 
    return redirect('/')    
  
if __name__ == '__main__':
    app.run(debug=True)
//templates/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Upload File and validate before save to Database using Python Flask PostgreSQL and SQLAlchemy </title>
  </head>
  <body>
  <h2>Upload File and validate before save to Database using Python Flask PostgreSQL and SQLAlchemy </h2>
  <h3>Select a file to upload</h3>
        <p>
         {% with messages = get_flashed_messages() %}
           {% if messages %}
          {% for message in messages %}
            <div class="alert alert-primary">
             <strong>{{ message }}</strong>
           </div>
          {% endfor %}
           {% endif %}
         {% endwith %}
        </p>
  <form method="post" action="/upload" enctype="multipart/form-data">
    First Name : <input type="text" name="fname" value="" placeholder="First Name" required>
    Last Name : <input type="text" name="lname" value="" placeholder="Last Name" required>
    <dl>
  <p>
   <input type="file" name="inputFile" autocomplete="off" required>
  </p>
    </dl>
    <p>
  <input type="submit" value="Submit">
 </p>
</form>
<style>
.alert-primary {
    color: #004085;
    background-color: #cce5ff;
    border-color: #b8daff;
}
.alert {
    position: relative;
    padding: .75rem 1.25rem;
    margin-bottom: 1rem;
    border: 1px solid transparent;
    border-radius: .25rem;
}
</style>
    </body>
</html>

Pagination using Python Flask PostgreSQL and SQLAlchemy

Pagination using Python Flask PostgreSQL and SQLAlchemy

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

Crate database table
CREATE TABLE students (
id serial PRIMARY KEY,
fname VARCHAR ( 40 ) NOT NULL,
lname VARCHAR ( 40 ) NOT NULL,
email VARCHAR ( 40 ) NOT NULL
);

SELECT * FROM students 

INSERT INTO students (fname, lname, email)
VALUES('cairocoders','ednalan', 'cairocoders@gmail.com');

Multiple insert
INSERT INTO
    students(id,fname,lname,email)
VALUES
    ('Quinn','Flynn'', 'Flynn'@gmail.com'),
    ('Tiger','nizon', 'nizon@gmail.com'),
    ('Airi','sato', 'sato@gmail.com');
 
#app.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
 
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
                                                      #password:admin
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:admin@localhost/sampledb'
 
db=SQLAlchemy(app)
 
class Student(db.Model):
  __tablename__='students'
  id=db.Column(db.Integer,primary_key=True)
  fname=db.Column(db.String(40))
  lname=db.Column(db.String(40))
  email=db.Column(db.String(40))
 
  def __init__(self,fname,lname,email):
    self.fname=fname
    self.lname=lname
    self.email=email
  
@app.route('/student/')
def student(page_num):
    student = Student.query.paginate(per_page=5, page=page_num, error_out=True)
    return render_template('index.html', student=student)
  
if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<html>
<head>
<title>Python Flask SQLAlchemy Pagination</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>   
</head>
<body>
<div class="container">
 <div class="row" style="padding: 20px;">
 <p><h2>Pagination using Python Flask PostgreSQL and SQLAlchemy</h2>  </p>
 <table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th><input type="checkbox" onclick="checkAll(this)"></th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
   {% for rs in student.items %}
   <tr>
                <td><input type="checkbox" name=""></td>
                <td>{{ rs.fname}}</td>
                <td>{{ rs.lname}}</td>
                <td>{{ rs.email}}</td>
            {% endfor %}
    </tr>        
        </tbody>
        <tfoot>
            <tr>
                <th></th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
            </tr>
        </tfoot>
    </table>
 </div>
  
   <ul class="pagination">
  {% if student.has_prev %}
   <li class="page-item"><a class="page-link" href="{{ url_for('student', page_num=student.prev_num) }}">Previous</a></li>
  {% else %}
   <li class="page-item disabled"><span class="page-link">Previous</span>
  {% endif %}
   </li>
    
  {% for page in student.iter_pages(left_edge=3, right_edge=3) %}
  {% if page %}
   <li class="page-item"><a class="page-link" href="{{ url_for('student', page_num=page) }}">{{ page }}</a></li>
  {% else %}
   <li class="page-item disabled" id="example_ellipsis"><a href="#" class="page-link">…</a></li> 
  {% endif %}
  {% endfor %}
  
  {% if student.has_next %}
   <li class="page-item"><a class="page-link" href="{{ url_for('student', page_num=student.next_num) }}">Next</a></li>
  {% else %}
   <li class="page-item disabled"><span class="page-link">Next</span>
  {% endif %}
   </ul>
 
</div>
<style>
table{
    width:100%;
}
#example_filter{
    float:right;
}
#example_paginate{
    float:right;
}
label {
    display: inline-flex;
    margin-bottom: .5rem;
    margin-top: .5rem;
    
}
.page-item.disabled .page-link {
    color: #6c757d;
    pointer-events: none;
    cursor: auto;
    background-color: #fff;
    border-color: #dee2e6;
}
</style>
<script>
function checkAll(bx) {
  var cbs = document.getElementsByTagName('input');
  for(var i=0; i < cbs.length; i++) {
    if(cbs[i].type == 'checkbox') {
      cbs[i].checked = bx.checked;
    }
  }
}
</script>  
</body>
</html>

Monday, May 10, 2021

Shopping Cart using Python Flask PostgreSQL

Shopping Cart using Python Flask PostgreSQL

install psycopg2 https://pypi.org/project/psycopg2/
Psycopg is the most popular PostgreSQL database adapter for the Python programming language.
(venv) PS C:\flaskmyproject> pip install psycopg2

CREATE TABLE product (
pid serial PRIMARY KEY,
code VARCHAR ( 100 ) NOT NULL,
name VARCHAR ( 100 ) NOT NULL,
image VARCHAR ( 100 ) NOT NULL,
category VARCHAR ( 50 ) NOT NULL,
price INT NOT NULL,
discount INT NOT NULL
);

Multiple insert
INSERT INTO
    product(code,name,image,category,price,discount)
VALUES
    ('00001','Samsung Galaxy A10S','2.jpg', 'Mobile', 520, 100),
    ('00002',, 'Samsung Galaxy Win Duos', '3.jpg', 'Mobile', 1600, 500),
    ('00003', 'Women Summer Spaghetti Strap Down', '4.jpg', 'Woman Dresess', 2020, 1250);

This shopping cart have no checkout option and payment option this is about to display product and add item to cart remove item from cart remove all items from cart

app.py
 
#app.py
from flask import Flask, session, render_template, request, redirect, url_for
import psycopg2 #pip install psycopg2 
import psycopg2.extras

app = Flask(__name__)

app.secret_key = "cairocoders-ednalan"

DB_HOST = "localhost"
DB_NAME = "sampledb"
DB_USER = "postgres"
DB_PASS = "admin"

conn = psycopg2.connect(dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

@app.route('/')
def products():
    cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

    cursor.execute("SELECT * FROM product")
    rows = cursor.fetchall()
    return render_template('products.html', products=rows)

@app.route('/add', methods=['POST'])
def add_product_to_cart():
    _quantity = int(request.form['quantity'])
    _code = request.form['code']
    # validate the received values
    if _quantity and _code and request.method == 'POST':

        cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

        cursor.execute('SELECT * FROM product WHERE code = %s', (_code,))
        row = cursor.fetchone()
                
        itemArray = { row['code'] : {'name' : row['name'], 'code' : row['code'], 'quantity' : _quantity, 'price' : row['price'], 'image' : row['image'], 'total_price': _quantity * row['price']}}
                
        all_total_price = 0
        all_total_quantity = 0
                
        session.modified = True
        if 'cart_item' in session:
            if row['code'] in session['cart_item']:
                for key, value in session['cart_item'].items():
                    if row['code'] == key:
                        old_quantity = session['cart_item'][key]['quantity']
                        total_quantity = old_quantity + _quantity
                        session['cart_item'][key]['quantity'] = total_quantity
                        session['cart_item'][key]['total_price'] = total_quantity * row['price']
            else:
                session['cart_item'] = array_merge(session['cart_item'], itemArray)
        
            for key, value in session['cart_item'].items():
                individual_quantity = int(session['cart_item'][key]['quantity'])
                individual_price = float(session['cart_item'][key]['total_price'])
                all_total_quantity = all_total_quantity + individual_quantity
                all_total_price = all_total_price + individual_price
        else:
            session['cart_item'] = itemArray
            all_total_quantity = all_total_quantity + _quantity
            all_total_price = all_total_price + _quantity * row['price']
            
        session['all_total_quantity'] = all_total_quantity
        session['all_total_price'] = all_total_price
                
        return redirect(url_for('products'))
    else:
        return 'Error while adding item to cart'

@app.route('/empty')
def empty_cart():
    try:
        session.clear()
        return redirect(url_for('.products'))
    except Exception as e:
        print(e)

@app.route('/delete/')
def delete_product(code):
    try:
        all_total_price = 0
        all_total_quantity = 0
        session.modified = True
        
        for item in session['cart_item'].items():
            if item[0] == code:    
                session['cart_item'].pop(item[0], None)
                if 'cart_item' in session:
                    for key, value in session['cart_item'].items():
                        individual_quantity = int(session['cart_item'][key]['quantity'])
                        individual_price = float(session['cart_item'][key]['total_price'])
                        all_total_quantity = all_total_quantity + individual_quantity
                        all_total_price = all_total_price + individual_price
                break
        
        if all_total_quantity == 0:
            session.clear()
        else:
            session['all_total_quantity'] = all_total_quantity
            session['all_total_price'] = all_total_price
            
        return redirect(url_for('.products'))
    except Exception as e:
        print(e)

def array_merge( first_array , second_array ):
    if isinstance( first_array , list ) and isinstance( second_array , list ):
        return first_array + second_array
    elif isinstance( first_array , dict ) and isinstance( second_array , dict ):
        return dict( list( first_array.items() ) + list( second_array.items() ) )
    elif isinstance( first_array , set ) and isinstance( second_array , set ):
        return first_array.union( second_array )
    return False

if __name__ == "__main__":
    app.run(debug=True)
templates/product.html
//templates/product.html
<!DOCTYPE html>
<html>
<head>
 <title>Shopping Cart using Python Flask PostgreSQL</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> 
<div class="container">
    <div class="row">
  <p><h2>Shopping Cart using Python Flask PostgreSQL</h2></p>
   <div class="col-sm-12">
        <div>
        {% with messages = get_flashed_messages() %}
            {% if messages %}
            <ul class=flashes>
            {% for message in messages %}
            <li>{{ message }}</li>
            {% endfor %}
            </ul>
            {% endif %}
        {% endwith %}
        </div>
  {% if 'cart_item' in session %}
   <p><a id="btnEmpty" href="{{ url_for('.empty_cart') }}" class="btn btn-danger">Empty Cart</a></p>
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Product</th>
                        <th>Quantity</th>
                        <th class="text-center">Unit Price</th>
                        <th class="text-center">Price</th>
                        <th> </th>
                    </tr>
                </thead>
                <tbody>
    {% for key, val in session['cart_item'].items() %}
        {% set quantity = session['cart_item'][key]['quantity'] %}
        {% set price = session['cart_item'][key]['price'] %}
        {% set item_price = session['cart_item'][key]['total_price'] %} 
                    <tr>
                        <td class="col-sm-8 col-md-6">
                        <div class="media">
                            <a class="thumbnail pull-left" href="#"> <img class="media-object" src="/static/images/{{ session['cart_item'][key]['image'] }}" style="width: 72px; height: 72px;"> </a>
                            <div class="media-body" style="padding-left:10px;">
                                <h4 class="media-heading"> <a href="#">{{ session['cart_item'][key]['name'] }}</a></h4>
                                <h5 class="media-heading"> by <a href="#">Brand name</a></h5>
                                <span>Status: </span><span class="text-success"><strong>In Stock</strong></span>
                            </div>
                        </div></td>
                        <td class="col-sm-1 col-md-1" style="text-align: center">
                        <input type="email" class="form-control" value="{{ quantity }}">
                        </td>
                        <td class="col-sm-1 col-md-1 text-center"><strong>${{ price }} </strong></td>
                        <td class="col-sm-1 col-md-1 text-center"><strong>${{ item_price }} </strong></td>
                        <td class="col-sm-1 col-md-1">
                        <a href="{{ url_for('.delete_product', code=session['cart_item'][key]['code']) }}" class="btn btn-danger">
                            <span class="glyphicon glyphicon-remove"></span> Remove
                        </a></td>
                    </tr>
    {% endfor %}
                    <tr>
                        <td colspan="4"><h5>Total Quantity</h5></td>
                        <td class="text-right"><h5><strong>{{ session['all_total_quantity'] }}</strong></h5></td>
                    </tr>
                    <tr>
                        <td colspan="3"><h3>Total</h3></td>
                        <td colspan="2" class="text-right"><h3><strong>$ {{ session['all_total_price'] }}</strong></h3></td>
                    </tr>
                    <tr>
                        <td colspan="4">
                        <button type="button" class="btn btn-default">
                            <span class="glyphicon glyphicon-shopping-cart"></span> Continue Shopping
                        </button></td>
                        <td>
                        <button type="button" class="btn btn-success">
                            Checkout <span class="glyphicon glyphicon-play"></span>
                        </button></td>
                    </tr>
                </tbody>
            </table>
  {% else: %}
   <div class="no-records">Your Cart is Empty</div>
  {% endif %}
        </div>
    </div>
</div>
               
<section class="our-publication pt-100 pb-70">
            <div class="container">
                <div class="section-header">
                    <i class="fa fa-book"></i>
                    <h2>Our Product</h2>
                    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod  labore et dolore magna aliqua.</p>
                </div>
                 
                <div class="row">
    {% for product in products %}
                    <div class="col-sm-6 col-lg-3"> 
      <form method="post" action="/add">
                        <div class="single-publication">
                            <figure style="width:263px;">
                                <a href="#">
                                    <img src="/static/images/{{ product.image }}">
                                </a>
                                <ul>
                                    <li><a href="#" title="Add to Favorite"><i class="fa fa-heart"></i></a></li>
                                    <li><a href="#" title="Add to Compare"><i class="fa fa-refresh"></i></a></li>
                                    <li><a href="#" title="Quick View"><i class="fa fa-search"></i></a></li>
                                </ul>
                            </figure>
 
                            <div class="publication-content">
                                <span class="category">{{ product.category }}</span>
                                <h3><a href="#">{{ product.name }}</a></h3>
                                <ul>
                                    <li><i class="icofont-star"></i></li>
                                    <li><i class="icofont-star"></i></li>
                                    <li><i class="icofont-star"></i></li>
                                    <li><i class="icofont-star"></i></li>
                                    <li><i class="icofont-star"></i></li>
                                </ul>
                                <h4 class="price">$ {{ product.price }}</h4>
                            </div>
 
                            <div class="add-to-cart">
        <input type="hidden" name="code" value="{{ product.code }}"/>
        <input type="text" class="product-quantity" name="quantity" value="1" size="2" />
        <input type="submit" value="Add to Cart" class="default-btn" />
                            </div>
                        </div>
      </form>
                    </div>
                {% endfor %}    
                     
                </div>
            </div>
        </section>
<style>
.pt-100 {
                padding-top: 100px;
            }
            .pb-70 {
                padding-bottom: 70px;
            }
            .section-header {
                margin-bottom: 60px;
                text-align: center;
            }
            .section-header i {
                color: #ff007d;
                font-size: 50px;
                display: inline-block;
                margin-bottom: 10px;
            }
            .section-header h2 {
                font-weight: bold;
                font-size: 34px;
                margin: 0;
            }
            .section-header p {
                max-width: 500px;
                margin: 20px auto 0;
            }
            .single-publication {
                border: 1px solid #f2eee2;
                margin-bottom: 30px;
                position: relative;
                overflow: hidden;
            }
            .single-publication figure {
                position: relative;
                margin: 0;
                text-align: center;
            }
            .single-publication figure > a {
                background-color: #fafafa;
                display: block;
            }
            .single-publication figure ul {
                list-style-type: none;
                padding: 0;
                margin: 0;
                position: absolute;
                right: -50px;
                top: 20px;
                transition: .6s;
                -webkit-transition: .6s;
            }
            .single-publication:hover figure ul {
                right: 15px;
            }
            .single-publication figure ul li a {
                display: inline-block;
                width: 35px;
                height: 35px;
                text-align: center;
                font-size: 15px;
                background: #ff007d;
                margin-bottom: 7px;
                border-radius: 50%;
                line-height: 35px;
                color: #fff;
            }
            .single-publication figure ul li a:hover {
                color: #fff;
                background: #e50663;
            }
            .single-publication .publication-content {
                text-align: center;
                padding: 20px;
            }
            .single-publication .publication-content .category {
                display: inline-block;
                font-family: 'Open Sans', sans-serif;
                font-size: 14px;
                color: #ff007d;
                font-weight: 600;
            }
            .single-publication .publication-content h3 {
                font-weight: 600;
                margin: 8px 0 10px;
                font-size: 20px;
            }
            .single-publication .publication-content h3 a {
                color: #1f2d30;
            }
            .single-publication .publication-content h3 a:hover {
                color: #ff007d;
            }
            .single-publication .publication-content ul {
                list-style-type: none;
                padding: 0;
                margin: 0;
                margin-bottom: 15px;
            }
            .single-publication .publication-content ul li {
                display: inline-block;
                font-size: 18px;
                color: #fec42d;
            }
            .single-publication .publication-content .price {
                font-size: 18px;
                color: #ff007d;
            }
            .single-publication .publication-content .price span {
                color: #6f6f6f;
                text-decoration: line-through;
                padding-left: 5px;
                font-weight: 300;
            }
            .single-publication .add-to-cart {
                position: absolute;
                right: 0;
                bottom: 0;
                left: 0;
                background: #fff;
                opacity: 0;
                visibility: hidden;
                text-align: center;
                -webkit-transform: scale(.7);
                transform: scale(.7);
                height: 105px;
                -moz-transition: .4s;
                -webkit-transition: .4s;
                transition: .4s;
            }
            .single-publication:hover .add-to-cart {
                visibility: visible;
                transform: scale(1);
                -webkit-transform: scale(1);
                opacity: 1;
            }
            .single-publication .add-to-cart .default-btn {
                margin-top: 28px;
                padding: 8px 25px;
                font-size: 14px;
            }
            .single-publication .category {
                margin: 0;
            }
            .single-publication .add-to-cart .default-btn {
                margin-top: 28px;
                padding: 8px 25px;
                font-size: 14px;
            }
            .default-btn {
                background-color: #ff007d;
                color: #fff;
                border: 1px solid #ff007d;
                display: inline-block;
                padding: 10px 30px;
                border-radius: 30px;
                text-transform: uppercase;
                font-weight: 600;
                font-family: 'Open Sans', sans-serif;
            }
            .default-btn:hover {
                color: #fff;
                text-decoration: none;
            }
</style>  
</body>
</html>
<//html>

SwiftUI how to create and use Form

SwiftUI how to create and use Form
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders on 5/5/21.
//  SwiftUI how to create and use Form

import SwiftUI

struct ContentView: View {
    @State var username: String = ""
    @State var isPrivate: Bool = true
    @State var notificationsEnabled: Bool = false
    @State private var previewIndex = 0

    var previewOptions = ["Always", "When Unlocked", "Never"]

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("PROFILE")) {
                    TextField("Username", text: $username)
                    Toggle(isOn: $isPrivate) {
                        Text("Private Account")
                    }
                }
                
                Section(header: Text("NOTIFICATIONS")) {
                    Toggle(isOn: $notificationsEnabled) {
                        Text("Enabled")
                    }
                    Picker(selection: $previewIndex, label: Text("Show Previews")) {
                        ForEach(0 ..< previewOptions.count) {
                            Text(self.previewOptions[$0])
                        }
                    }
                }
                
                Section(header: Text("ABOUT")) {
                    HStack {
                        Text("Version")
                        Spacer()
                        Text("1.0.0")
                    }
                }
                
                Section {
                    Button(action: {
                        print("Perform an action here...")
                    }) {
                        Text("Reset All Settings")
                    }
                }
            }
            .navigationBarTitle("Settings")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ContentView()
        }
    }
}

Saturday, May 8, 2021

SwiftUI Form Picker How to get value from for loop

SwiftUI Form Picker How to get value from for loop
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//  

import SwiftUI

struct ContentView: View {
    
    @State private var location = ""

    var body: some View {
        NavigationView {
            Form {
                Picker(selection: $location,
                   label: Text("Location")) {
                    ForEach(Location.allLocations, id: \.self) { location in
                        Text(location).tag(location)
                    }
                }
            }
        }
    }
}

struct Location {
    static let allLocations = [
        "New York",
        "London",
        "Tokyo",
        "Berlin",
        "Olongapo",
        "Paris"
    ]
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ContentView()
        }
    }
}

SwiftUI How to make view fill width or height of screen

SwiftUI How to make view fill width or height of screen
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Full size text view!")
            .foregroundColor(Color.white)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.blue)
    }
}

struct SecondView: View {
    var body: some View {
        VStack {
            Text("VStack Text View")
                .foregroundColor(Color.white)
                .background(Color.blue)
        }.frame(maxWidth: .infinity, maxHeight: .infinity)
            .border(Color.red, width: 2) // Set VStack border to make it visible
        
    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ContentView()
            SecondView()
        }
    }
}

SwiftUI Login Register Form

SwiftUI Login Register Form
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

let lightGreyColor = Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0)

struct ContentView: View {
    
    @State var username: String = ""
    @State var password: String = ""
    
    @State var authenticationDidFail: Bool = false
    
    var body: some View {
        NavigationView {
            VStack {
                Text("Welcome!")
                    .font(.largeTitle)
                    .fontWeight(.semibold)
                    .padding(.bottom, 20)
                
                Image("login")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 150, height: 150)
                    .clipped()
                    .cornerRadius(150)
                    .padding(.bottom, 75)
                
                TextField("Username", text: $username)
                    .padding()
                    .background(lightGreyColor)
                    .cornerRadius(5.0)
                    .padding(.bottom, 20)
                    .shadow(radius: 5)
                
                SecureField("Password", text: $password)
                    .padding()
                    .background(lightGreyColor)
                    .cornerRadius(5.0)
                    .padding(.bottom, 20)
                    .shadow(radius: 5)
                
                Button(action: {}) {
                    Text("LOGIN")
                        .font(.headline)
                        .foregroundColor(.white)
                        .padding()
                        .frame(width: 220, height: 60)
                        .background(Color.green)
                        .cornerRadius(15.0)
                        .shadow(radius: 5)
                        .border(Color.red, width: 4)
                }
                
               VStack {
                    Text("Create Account")
                    NavigationLink(destination: ContentViewregister()) {
                        Text("Register")
                    }
                }
               .padding()
            }
            .padding()
        }
    }
        
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ContentView()
            ContentViewregister()
        }
    }
}

struct Location {
    static let allLocations = [
        "New York",
        "London",
        "Tokyo",
        "Berlin",
        "Olongapo",
        "Paris"
    ]
}
struct ContentViewregister : View {
    
    @State private var firstname = ""
    @State private var lastname = ""
    @State private var location = ""
    @State private var termsAccepted = false
    @State private var age = 20

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Register")) {
                    TextField("Firstname",
                              text: $firstname)
                    TextField("Lastname",
                              text: $lastname)
                    Picker(selection: $location,
                           label: Text("Location")) {
                            ForEach(Location.allLocations, id: \.self) { location in
                                Text(location).tag(location)
                            }
                    }
                    
                    Toggle(isOn: $termsAccepted,
                           label: {
                            Text("Accept terms and conditions")
                    })
                    
                    Stepper(value: $age,
                            in: 18...100,
                            label: {
                        Text("Current age: \(self.age)")
                    })
                    
                    Button(action: {}) {
                        Text("Register")
                            .font(.headline)
                            .foregroundColor(.white)
                            .padding()
                            .frame(width: 220, height: 60)
                            .background(Color.green)
                            .cornerRadius(15.0)
                            .shadow(radius: 5)
                            .border(Color.red, width: 4)
                    }
                    .padding()
                }
            }.navigationBarTitle(Text("Register"))
        }
    }
}

Friday, May 7, 2021

SwiftUI How to build a Login Screen

SwiftUI How to build a Login Screen
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders 
//

import SwiftUI

struct ContentView: View {
    
    @State private var email = ""
    @State private var password = ""
    
    var body: some View {
        VStack() {
            Text("Login")
                .font(.largeTitle).foregroundColor(Color.white)
                .padding([.top, .bottom], 40)
                .shadow(radius: 10.0, x: 20, y: 10)
            
            Image("login")
                .resizable()
                .frame(width: 250, height: 250)
                .clipShape(Circle())
                .overlay(Circle().stroke(Color.white, lineWidth: 4))
                .shadow(radius: 10.0, x: 20, y: 10)
                .padding(.bottom, 50)
            
            VStack(alignment: .leading, spacing: 15) {
                TextField("Email", text: self.$email)
                    .padding()
                    .background(Color.themeTextField)
                    .cornerRadius(10.0)
                    .shadow(radius: 10.0, x: 20, y: 10)
                
                SecureField("Password", text: self.$password)
                    .padding()
                    .background(Color.themeTextField)
                    .cornerRadius(10.0)
                    .shadow(radius: 10.0, x: 20, y: 10)
            }.padding([.leading, .trailing], 27.5)
            
            Button(action: Submit) {
                Text("Sign In")
                    .font(.headline)
                    .foregroundColor(.white)
                    .padding()
                    .frame(width: 300, height: 50)
                    .background(Color.blue)
                    .cornerRadius(15.0)
                    .shadow(radius: 10.0, x: 20, y: 10)
            }.padding(.top, 50)
            
            
            Spacer()
            HStack(spacing: 0) {
                Text("Don't have an account? ")
                Button(action: {}) {
                    Text("Sign Up")
                        .foregroundColor(.black)
                }
            }
        }
        .background(
            LinearGradient(gradient: Gradient(colors: [.yellow, .orange]), startPoint: .top, endPoint: .bottom)
                .edgesIgnoringSafeArea(.all))
        
    }
    
    func Submit() {
        print("Successfully Login")
        print(self.$email)
        print(self.$password)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

extension Color {
    static var themeTextField: Color {
        return Color(red: 220.0/255.0, green: 230.0/255.0, blue: 230.0/255.0, opacity: 1.0)
    }
}

SwiftUI How to adjust the position of a view using its offset

SwiftUI How to adjust the position of a view using its offset
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Home")
                .background(Color.red)
            Text("Options")
                .offset(y: 15)
                .padding(.bottom, 15)
            Text("Help")
                .offset(y: 15)
                .padding(.bottom, 25)
            
            ZStack (alignment: .bottomTrailing) {
                Image("luppypic")
                    .resizable()
                    .frame(width: 250, height: 250, alignment: .center)
                Text("Luppy picture")
                    .padding(4)
                    .background(Color.black)
                    .foregroundColor(.white)
                    .offset(x: -5, y: -5)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Home")
                .background(Color.red)
                .offset(y: 15)
            Text("Options")
                .offset(y: 15)
                .padding(.bottom, 15)
            Text("Help")
                .background(Color.red)
            
            
            ZStack(alignment: .bottomTrailing){
                Image("luppy")
                Text("Luppy Photo")
                    .padding(4)
                    .background(Color.black)
                    .foregroundColor(.white)
                    .offset(x: -5, y: -5)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

SwiftUI How to show a popover view

SwiftUI How to show a popover view
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State private var showpopover = false
    
    var body: some View {
        Button("Show menu") {
            showpopover = true
        }
        .popover(isPresented: $showpopover) {
            Text("Your content here")
                .font(.headline)
                .padding()
        }
           
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

SwiftUI How to let users pick options from a menu

SwiftUI How to let users pick options from a menu
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct SecondView: View {
    var body: some View{
        Text("This is a second view details")
    }
}
struct ContentView: View {
    var body: some View {
        NavigationView{
            VStack {
                NavigationLink(destination: SecondView()) {
                   Text("Show Details View")
                }
                .navigationTitle("Navigation")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

SwiftUI How to let users pick options from a menu

SwiftUI How to let users pick options from a menu
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State private var selection = "Red"
    let colors = ["Red", "Green", "Blue", "Black"]
    
    var body: some View {
        VStack {
            Picker("Select a paint color", selection: $selection) {
                ForEach(colors, id: \.self) {
                    Text($0)
                }
            }
            .pickerStyle(MenuPickerStyle())
            
            Text("Selected color: \(selection)")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

SwiftUI How to show a menu when a button is pressed

SwiftUI How to show a menu when a button is pressed
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        Menu("Options") {
            Button("Order Now", action: placeorder)
            Button("Adjust Oder", action: adjustorder)
            Menu("Advanced") {
                Button("Rename", action: rename)
                Button("Delay", action: delay)
            }
            Button("Cancel", action: canceloder)
        }
    }
    
    func placeorder() {
        print("Order succesfully")
    }
    func adjustorder() {
        print("Order Adjusted")
    }
    func canceloder() {
        print("Order Cancel")
    }
    func rename() {
        print("Order Rename")
    }
    func delay() {
        print("Delay order")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Wednesday, May 5, 2021

SwiftUI How to add actions to alert buttons

SwiftUI How to add actions to alert buttons

SwiftUI How to add actions to alert buttons

this example if you want to attach actions to buttons to perfom specific actions
 
//
//  ContentView.swift
//  Testapp
//
//  Created by Cairocoders on 5/5/21.
//

import SwiftUI

struct ContentView: View {

    @State private var showingAlert = false

    var body: some View {
	
        Button("Show Alert") {
            showingAlert = true
        }
        .alert(isPresented:$showingAlert) {
            Alert(
                title: Text("Are you sure you want to delete this?"),
                message: Text("There is no undo"),
                primaryButton: .destructive(Text("Delete")) {
                    print("Deleted")
                },
                secondaryButton: .cancel()
            )
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
        
    }
}

Related Post