article

Wednesday, August 25, 2021

SwiftUI List View Deletion and List View Dragging

SwiftUI List View Deletion and List View Dragging

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {

    @State var data = ["Record-1","Record-2","Record-3","Record-4","Record-5","Record-6"]
    
    var body : some View{
        
        NavigationView{
            
            List{
                
                ForEach(data,id: \.self){i in
                    Text(i)
                }.onDelete(perform: { (index) in
                    
                    self.data.remove(atOffsets: index)
                    
                }).onMove(perform: { (index, destination) in
                    
                    self.data.move(fromOffsets: index, toOffset: destination)
                    
                })

            }.navigationBarTitle("ListView")
            .navigationBarItems(trailing: EditButton())
        }
    }
}

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

SwiftUI Swipeable Card View Tinder-Style

SwiftUI Swipeable Card View Tinder-Style

In this tutorial When one is removed, another is added to the bottom of the stack.

ContentView.swift
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct User: Hashable, CustomStringConvertible {
    var id: Int
    
    let firstName: String
    let lastName: String
    let age: Int
    let mutualFriends: Int
    let imageName: String
    let occupation: String
    
    var description: String {
        return "\(firstName), id: \(id)"
    }
}

struct ContentView: View {
    
    /// List of users
    @State var users: [User] = [
        User(id: 0, firstName: "Airi", lastName: "Satou", age: 33, mutualFriends: 43, imageName: "photo1", occupation: "Accountant"),
        User(id: 1, firstName: "Angeleca", lastName: "Ramos", age: 47, mutualFriends: 12, imageName: "photo2", occupation: "Junior Techinical Author"),
        User(id: 2, firstName: "Aston", lastName: "Cox", age: 20, mutualFriends: 10, imageName: "photo3", occupation: "Scientist"),
        User(id: 3, firstName: "Bradley", lastName: "Greer", age: 45, mutualFriends: 46, imageName: "photo4", occupation: "Sales Assistant"),
        User(id: 4, firstName: "Bruno", lastName: "Nash", age: 23, mutualFriends:48, imageName: "photo5", occupation: "Sales Assistant"),
        User(id: 5, firstName: "Cara", lastName: "Stevens", age: 24, mutualFriends: 37, imageName: "photo6", occupation: "Marketing Manager")
    ]
    
    /// Return the CardViews width for the given offset in the array
    /// - parameters: - geometry: The geometry proxy of the parent, - id: The ID of the current user
    private func getCardWidth(_ geometry: GeometryProxy, id: Int) -> CGFloat {
        let offset: CGFloat = CGFloat(users.count - 1 - id) * 10
        return geometry.size.width - offset
    }
    
    /// Return the CardViews frame offset for the given offset in the array
    /// - Parameters: - geometry: The geometry proxy of the parent, - id: The ID of the current user
    private func getCardOffset(_ geometry: GeometryProxy, id: Int) -> CGFloat {
        return  CGFloat(users.count - 1 - id) * 10
    }
    
    private var maxID: Int {
        return self.users.map { $0.id }.max() ?? 0
    }
    
    var body: some View {
        VStack {
            GeometryReader { geometry in
                LinearGradient(gradient: Gradient(colors: [Color.init(#colorLiteral(red: 0.8509803922, green: 0.6549019608, blue: 0.7803921569, alpha: 1)), Color.init(#colorLiteral(red: 1, green: 0.9882352941, blue: 0.862745098, alpha: 1))]), startPoint: .bottom, endPoint: .top)
                    .frame(width: geometry.size.width * 1.5, height: geometry.size.height)
                    .background(Color.blue)
                    .clipShape(Circle())
                    .offset(x: -geometry.size.width / 4, y: -geometry.size.height / 2)
                
                VStack(spacing: 24) {
                    DateView()
                    ZStack {
                        ForEach(self.users, id: \.self) { user in
                            // Range Operator
                            if (self.maxID - 3)...self.maxID ~= user.id {
                                CardView(user: user, onRemove: { removedUser in
                                    // Remove that user from our array
                                    self.users.removeAll { $0.id == removedUser.id }
                                })
                                    .frame(width: self.getCardWidth(geometry, id: user.id), height: 400)
                                    .offset(x: 0, y: self.getCardOffset(geometry, id: user.id))
                            }
                        }
                    }
                    Spacer()
                }
            }
        }.padding()
    }
}

struct DateView: View {
    var body: some View {
        VStack {
            HStack {
                VStack(alignment: .leading) {
                    Text(Date(), style: .date)
                        .font(.title)
                        .bold()
                    Text("Today")
                        .font(.subheadline)
                        .foregroundColor(.gray)
                }
                Spacer()
            }.padding()
        }
        .background(Color.white)
        .cornerRadius(10)
        .shadow(radius: 5)
    }
}

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

import SwiftUI

struct CardView: View {
    
    @State private var translation: CGSize = .zero
    @State private var swipeStatus: LikeDislike = .none
    
    private var user: User
    private var onRemove: (_ user: User) -> Void
    
    private var thresholdPercentage: CGFloat = 0.5 // when the user has draged 50% the width of the screen in either direction
    
    private enum LikeDislike: Int {
        case like, dislike, none
    }
    
    init(user: User, onRemove: @escaping (_ user: User) -> Void) {
        self.user = user
        self.onRemove = onRemove
    }
    
    /// What percentage of our own width have we swipped - Parameters: - geometry: The geometry - gesture: The current gesture translation value
    private func getGesturePercentage(_ geometry: GeometryProxy, from gesture: DragGesture.Value) -> CGFloat {
        gesture.translation.width / geometry.size.width
    }
    
    var body: some View {
        GeometryReader { geometry in
            VStack(alignment: .leading) {
                 ZStack(alignment: self.swipeStatus == .like ? .topLeading : .topTrailing) {
                    Image(self.user.imageName)
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: geometry.size.width, height: geometry.size.height * 0.75)
                        .clipped()
                    
                    if self.swipeStatus == .like {
                        Text("LIKE")
                            .font(.headline)
                            .padding()
                            .cornerRadius(10)
                            .foregroundColor(Color.green)
                            .overlay(
                                RoundedRectangle(cornerRadius: 10)
                                    .stroke(Color.green, lineWidth: 3.0)
                        ).padding(24)
                            .rotationEffect(Angle.degrees(-45))
                    } else if self.swipeStatus == .dislike {
                        Text("DISLIKE")
                            .font(.headline)
                            .padding()
                            .cornerRadius(10)
                            .foregroundColor(Color.red)
                            .overlay(
                                RoundedRectangle(cornerRadius: 10)
                                    .stroke(Color.red, lineWidth: 3.0)
                        ).padding(.top, 45)
                            .rotationEffect(Angle.degrees(45))
                    }
                }
                
                HStack {
                    VStack(alignment: .leading, spacing: 6) {
                        Text("\(self.user.firstName) \(self.user.lastName), \(self.user.age)")
                            .font(.title)
                            .bold()
                        Text(self.user.occupation)
                            .font(.subheadline)
                            .bold()
                        Text("\(self.user.mutualFriends) Mutual Friends")
                            .font(.subheadline)
                            .foregroundColor(.gray)
                    }
                    Spacer()
                    
                    Image(systemName: "info.circle")
                        .foregroundColor(.gray)
                }
                .padding(.horizontal)
            }
            .padding(.bottom)
            .background(Color.white)
            .cornerRadius(10)
            .shadow(radius: 5)
            .animation(.interactiveSpring())
            .offset(x: self.translation.width, y: 0)
            .rotationEffect(.degrees(Double(self.translation.width / geometry.size.width) * 25), anchor: .bottom)
            .gesture(
                DragGesture()
                    .onChanged { value in
                        self.translation = value.translation
                        
                        if (self.getGesturePercentage(geometry, from: value)) >= self.thresholdPercentage {
                            self.swipeStatus = .like
                        } else if self.getGesturePercentage(geometry, from: value) <= -self.thresholdPercentage {
                            self.swipeStatus = .dislike
                        } else {
                            self.swipeStatus = .none
                        }
                        
                }.onEnded { value in
                    // determine snap distance > 0.5 aka half the width of the screen
                        if abs(self.getGesturePercentage(geometry, from: value)) > self.thresholdPercentage {
                            self.onRemove(self.user)
                        } else {
                            self.translation = .zero
                        }
                    }
            )
        }
    }
}

struct CardView_Previews: PreviewProvider {
    static var previews: some View {
        CardView(user: User(id: 1, firstName: "Cairocoders", lastName: "Tutorial101", age: 27, mutualFriends: 0, imageName: "photo1", occupation: "Coder"),
                 onRemove: { _ in
                    // do nothing
            })
            .frame(height: 400)
            .padding()
    }
}

Wednesday, August 18, 2021

ReactJS Events

ReactJS Events

An event is an action that could be triggered as a result of the user action or system generated event. For example, a mouse click, loading of a web page, pressing a key, window resizes, and other interactions are called events.

React events are written in camelCase syntax:

onClick instead of onclick.

React event handlers are written inside curly braces:

onClick={shoot}  instead of onClick="shoot()".
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  //Event Handlers
  //shoot() {
  //  alert("Great Shot!");
  //}
  shoot = (a) => {
    alert(a);
  }
  render() {
    return (
      <div>
        <h1>Hello, world! React Events</h1>
      <button onClick={this.shoot}>Take the shot!</button> <br/>
      <button onClick={() => this.shoot("Passing Arguments - If you want to send parameters into an event handler, you have two options")}>Take the shot!</button>
      </div>
    );
  }
}
export default App;
Example 2
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  constructor(props) {
     super(props);
     
     this.state = {
        data: 'Initial data...'
     }
     this.updateState = this.updateState.bind(this);
  };
  //onClick event that will trigger updateState function once the button is clicked.
  updateState() {
     this.setState({data: 'Data updated...'})
  }
  render() {
     return (
        <div>
           <button onClick = {this.updateState}>CLICK</button>
           <h4>{this.state.data}</h4>
        </div>
     );
  }
}
export default App;
Example 3
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  constructor(props) {
     super(props);
     
     this.state = {
        data: 'Initial data...'
     }
     this.updateState = this.updateState.bind(this);
  };
  updateState() {
     this.setState({data: 'Data updated from the child component...'})
  }
  render() {
     return (
        <div>
           <Content myDataProp = {this.state.data} 
              updateStateProp = {this.updateState}></Content>
        </div>
     );
  }
}
//Child Events
class Content extends React.Component {
  render() {
     return (
        <div>
           <button onClick = {this.props.updateStateProp}>CLICK</button>
           <h3>{this.props.myDataProp}</h3>
        </div>
     );
  }
}
export default App;
Example 4
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  render() {
     return (
        <div>
          <form onSubmit={handleSubmit}>
            <button type="submit">Submit</button>
          </form>
        </div>
     );
  }
}
function handleSubmit(e) {
  e.preventDefault();
  console.log('You clicked submit.');
}
export default App;
Example 5
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
    //this Toggle component renders a button that lets the user toggle between “ON” and “OFF” states
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}
export default App;
Example 6 src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={() => this.handleClick()}>
        Click me
      </button>
    );
  }
}
export default App;
Example 7
src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: ""
    };
  }
  //event handlers
  changeText(event) {
      this.setState({
      name: event.target.value
    });
  }
  render() {
    return (
      <div>
      <label htmlFor="name">Enter Text here </label>
      <input type="text" id="name" onChange={this.changeText.bind(this)} />
      <h3>{this.state.name}</h3>
      </div>
    );
  }
}
export default App;
Example 8 src/App.js
//src/App.js
import React from 'react';
//React Events
class App extends React.Component {
  constructor(props) {  
    super(props);  
    this.state = {  
        yourName: ''  
    };  
}  
changeText(event) {  
    this.setState({  
      yourName: event.target.value  
    });  
}  
render() {
    return (
      <div>  
      <h2>Simple Event Example</h2>  
      <label htmlFor="name">Enter Your name: </label>  
      <input type="text" id="yourName" onChange={this.changeText.bind(this)}/>  
      <h4>You entered: { this.state.yourName }</h4>  
      </div>
    );
  }
}
export default App;

ReactJS Lifecycle

ReactJS Lifecycle

Each component in React has a lifecycle which you can monitor and manipulate during its three main phases.

The three phases are: Mounting, Updating, and Unmounting.


src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
 
//src/App.js
import React from 'react';
//React Lifecycle
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  //The getDerivedStateFromProps method is called right before the render method:
  //static getDerivedStateFromProps(props, state) {
  //  return {favoritecolor: props.favcol };
  //}

  //The componentDidMount() method is called after the component is rendered.
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }

  //getDerivedStateFromProps method This is the first method that is called when a component gets updated.
  //static getDerivedStateFromProps(props, state) {
  //  return {favoritecolor: props.favcol };
  //}
  //shouldComponentUpdate() method you can return a Boolean value that specifies whether React should continue with the rendering or not.
  //shouldComponentUpdate() {
  //  return true;
  //}

  //changeColor = () => {
  //  this.setState({favoritecolor: "blue"});
  //}

  //getSnapshotBeforeUpdate() method you have access to the props and state before the update, meaning that even after the update, you can check what the values were before the update.
  getSnapshotBeforeUpdate(prevProps, prevState) {
    document.getElementById("div1").innerHTML =
    "Before the update, the favorite was " + prevState.favoritecolor;
  }
  //componentDidUpdate method is called after the component is updated in the DOM.
  componentDidUpdate() {
    document.getElementById("div2").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }  
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      <div id="div1"></div>
      <div id="div2"></div>
      </div>
    );
  }
}

export default App;
Example 2
src/App.js
 
//src/App.js
import React from 'react';
//React Lifecycle
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {show: true};
  }
  delHeader = () => {
    this.setState({show: false});
  }
  render() {
    let myheader;
    if (this.state.show) {
      myheader = <Child />;
    };
    return (
      <div>
      {myheader}
      <button type="button" onClick={this.delHeader}>Delete Header</button>
      </div>
    );
  }
}
//componentWillUnmount method is called when the component is about to be removed from the DOM.
class Child extends React.Component {
  componentWillUnmount() {
    alert("The component named Header is about to be unmounted.");
  }
  render() {
    return (
      <h1>Hello World!</h1>
    );
  }
}

export default App;
Example 3
src/App.js
 
//src/App.js
import React from 'react';
//React Lifecycle
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

export default App;

Tuesday, August 17, 2021

ReactJS State

ReactJS State

The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders.
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
import React from 'react';
//state Object
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      brand: "Ford",
      model: "Mustang",
      color: "red",
      year: 1964
    };
  }
  //Changing the state Object
  changeColor = () => {
    this.setState({color: "blue"});
  }
  render() {
    return (
      <div>
        <h1>My {this.state.brand}</h1>
        <p>
          It is a {this.state.color}
          {this.state.model}
          from {this.state.year}.
        </p>
        <button
          type="button"
          onClick={this.changeColor}
        >Change color</button>
      </div>
    );
  }
}

export default App;
src/App.js
import React from 'react';
//Local State
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
    </div>
    );
  }
}

export default App;

ReactJS Simple Guide to Component Props

ReactJS Simple Guide to Component Props 

React Props
React Props are like function arguments in JavaScript and attributes in HTML.

To send props into a component, use the same syntax as HTML attributes:
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/app.js
import React from 'react';
import { Component } from 'react'; //Class component props
//React Props 
class App extends React.Component {
  render() {
     return (
        <div>
           <HelloWorld/>
           <Hello who="Earth" />
           <Message greet="Welcome" who="Aliens" /> 
           <HelloAsClass who="Earth" />
           <Valuesofprops prop="My String Value" />
           <HelloPeople persons={['Joker', 'Batman']} />
           <HelloOptional />
           <Message2 greet={hiBatman.greet} who={hiBatman.who} />
           <Parent>
            <span>I'm a child!</span>
           </Parent>
        </div>
     );
  }
}

function HelloWorld() {
  return <span>Hello, World!</span>;
}
function Hello(props) {
   return <div>Hello, {props.who}!</div>;
 }
//Multiple props
function Message({ greet, who }) {
   return <div>{greet}, {who}!</div>;
 }
//Class component props
class HelloAsClass extends Component {
   render() {
     return <div>Hello, {this.props.who}!</div>;
   }
 }

function Valuesofprops({ prop }) {
   return <div>{prop}</div>;
}
//Passing down props
function HelloPeople({ persons }) {
   return (
     <div>
       {persons.map((person, index) => {
         return <Hello who={person} key={index} />;
       })}
     </div>
   );
 }
 function HelloOptional({ who = 'Unknown' }) {
   return <div>Hello, {who}!</div>;
 }
//Props spread syntax
const hiBatman = { greet: 'Hi', who: 'Batman' };

function Message2({ greet, who }) {
  return <div>{greet}, {who}!</div>;
}
//Special props children
function Parent({ children }) {
   console.log(children); // logs <span>I'm a child!</span>
   return <div>{children}</div>;
 }

export default App;

Sunday, August 15, 2021

SwiftUI Move Rows from List

SwiftUI Move Rows from List

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @State private var numbers = ["One", "Two", "Three", "Four", "Five"]
    
    var body: some View {
        NavigationView {
            List {
                ForEach(numbers, id: \.self) { number in
                    Text(number)
                }
                .onMove { (indexSet, index) in
                    self.numbers.move(fromOffsets: indexSet,
                                    toOffset: index)
                }
            
            .navigationBarTitle(Text("Move Rows From List"))
            }
            .navigationBarItems(trailing: EditButton())
        }
    }
}

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

Friday, August 13, 2021

ReactJS Components Example

ReactJS Components Example

Components are like functions that return HTML elements.

React Components
Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML via a render() function.

Components come in two types, Class components and Function components, in this tutorial we will concentrate on Class components.

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
src/app.js
import React from 'react';
//Create a Class Component
//class App extends React.Component {
//  render() {
//    return <h2>Hi, I am a Car!</h2>;
//  }
//}

//Function Component
//function App() {
//  return <h2>Hi, I am also a Car!</h2>;
//}

//Component Constructor
//class App extends React.Component {
//  constructor() {
//    super();
//    this.state = {color: "red"};
//  }
//  render() {
//    return <h2>I am a {this.state.color} Car!</h2>;
//  }
//}

//Components in Components
class Car extends React.Component {
  render() {
    return <h2>I am a Car!</h2>;
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
      <h1>Who lives in my Garage?</h1>
      <Car />
      </div>
    );
  }
}
export default App;
src/app.js
import React from 'react';

class App extends React.Component {
  render() {
     return (
        <div>
           <Header/>
           <Content/>
           <Footer/>
        </div>
     );
  }
}
class Header extends React.Component {
  render() {
     return (
        <div>
           <h1>Header</h1>
        </div>
     );
  }
}
class Content extends React.Component {
  render() {
     return (
        <div>
           <h2>Content</h2>
           <p>The content text!!!</p>
        </div>
     );
  }
}
class Footer extends React.Component {
  render() {
     return (
        <div>
           <h2>Copyright @2021</h2>
        </div>
     );
  }
}
export default App;
src/app.js
import React from 'react';
//Stateful Example - set the state for owner component (App)
//TableRow for every object from the data array.
class App extends React.Component {
  constructor() {
    super();
    this.state = {
       data: 
       [
          {
             "id":1,
             "name":"Cairocoders",
             "age":"31"
          },
          {
             "id":2,
             "name":"Clyde",
             "age":"45"
          },
          {
             "id":3,
             "name":"Caite",
             "age":"40"
          }
       ]
    }
 }
  render() {
     return (
        <div>
           <Header/>
           <table>
               <tbody>
                  {this.state.data.map((person, i) => <TableRow key = {i} 
                     data = {person} />)}
               </tbody>
            </table>
           <Content/>
           <Footer/>
        </div>
     );
  }
}
class Header extends React.Component {
  render() {
     return (
        <div>
           <h1>Header</h1>
        </div>
     );
  }
}
class Content extends React.Component {
  render() {
     return (
        <div>
           <h2>Content</h2>
           <p>The content text!!!</p>
        </div>
     );
  }
}
class Footer extends React.Component {
  render() {
     return (
        <div>
           <h2>Copyright @2021</h2>
        </div>
     );
  }
}

class TableRow extends React.Component {
  render() {
     return (
        <tr>
           <td>{this.props.data.id}</td>
           <td>{this.props.data.name}</td>
           <td>{this.props.data.age}</td>
        </tr>
     );
  }
}
export default App;
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>

    <div id="root"></div>
</body>
</html>

SwiftUI Header and Footer List

SwiftUI Header and Footer List
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    let toyota = ["Corolla","Camry","Yaris"]
    let honda = ["HR-V","Odyssey","Mobelio"]
    
    var body: some View {
        NavigationView {
            List {
                Section(header:
                    Text("Toyota")) {
                        ForEach(0 ..< toyota.count) {
                            Text(self.toyota[$0])
                        }
                    }
                Section(header:
                    HStack {
                        Image(systemName: "car")
                        Text("Honda")
                    }
                , footer: Text("This is a example list of a few car brands").font(.footnote))  {
                               ForEach(0 ..< honda.count) {
                                   Text(self.honda[$0])
                               }
                           }
            
            } .navigationBarTitle("Cars")
        }
           
    }
}

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

Thursday, August 12, 2021

SwiftUI Spacer sample aligned parent view

SwiftUI Spacer sample aligned parent view
Spacers can be used to push align views horizontally or vertically aligned at the top-left, middle and bottom-toght of their parent view
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            HStack {
                Text("Text Left")
                Image(systemName: "arrow.left.circle.fill")
                Spacer()
            }.padding()
            
            Spacer()
            HStack {
                Image(systemName: "arrow.left.circle.fill")
                Spacer()
                Text("Text Center")
                Spacer()
                Image(systemName: "arrow.right.circle.fill")
            }.padding()
            
            Spacer()
            HStack {
                Spacer()
                Image(systemName: "arrow.right.circle.fill")
                Text("Text Right")
            }.padding()
            
        }
        .foregroundColor(Color.white)
        .background(RoundedRectangle(cornerRadius: 10))
        .foregroundColor(Color.gray)
        .font(.largeTitle)
        .padding()
    }
}

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

SwiftUI Simple Delete Rows from List

SwiftUI Simple Delete Rows from List
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @State private var recipes = ["Bistek Tagalog", "Sinigang Na Baboy", "Ginisang Munggo", "Pork Estofado", "Pata Tim"]

    var body: some View {
    
        NavigationView {
            List {
                ForEach(recipes, id: \.self) { recipe in
                    Text(recipe)
                }
                .onDelete(perform: self.deleteRow)
            }
            .navigationBarTitle(Text("Recipes"))
        }
    }
    private func deleteRow(at indexSet: IndexSet) {
        self.recipes.remove(atOffsets: indexSet)
    }
}

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

SwiftUI circular progress View

SwiftUI circular progress View
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State private var downloadAmount = 0.0
    var body: some View {
        NavigationView {
            VStack {
                ProgressView("Downloading…", value: downloadAmount, total: 100)
                    .progressViewStyle(CirclerPercentageProgressViewStyle())
                    .frame(width: 120, height: 120, alignment: .center)
                .padding()
                Button(action: {
                    withAnimation {
                        if downloadAmount < 100 {
                            downloadAmount += 10
                        }
                    }
                }, label: {
                    Text("+10%")
                })
            }
                
            .navigationBarTitle("ProgressView", displayMode: .inline)
        }
        
    }
}

public struct CirclerPercentageProgressViewStyle : ProgressViewStyle {
    public func makeBody(configuration: LinearProgressViewStyle.Configuration) -> some View {
        VStack(spacing: 10) {
            configuration.label
                .foregroundColor(Color.secondary)
            ZStack {
                Circle()
                    .stroke(lineWidth: 15.0)
                    .opacity(0.3)
                    .foregroundColor(Color.accentColor.opacity(0.5))
                
                Circle()
                    .trim(from: 0.0, to: CGFloat(configuration.fractionCompleted ?? 0))
                .stroke(style: StrokeStyle(lineWidth: 15.0, lineCap: .round, lineJoin: .round))
                .foregroundColor(Color.accentColor)
                
                Text("\(Int((configuration.fractionCompleted ?? 0) * 100))%")
                    .font(.headline)
                    .foregroundColor(Color.secondary)
            }
        }
    }
}

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

Wednesday, August 11, 2021

SwiftUI Search Bar with Animations

SwiftUI Search Bar with Animations
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {

    @State private var searchText = ""
    @State private var isEditing = false
    
    let countryList = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: $0) }
    var body: some View {
            NavigationView {
                List {
                    Section.init(header: SearchBar(text: $searchText, isEditing: $isEditing),
                    content: {
                        ForEach(countryList.filter( { searchText.isEmpty ? true : $0.contains(searchText) } ), id: \.self) { country in
                            Text(country)
                        }
                    })
                }
            .navigationTitle("Demo")
            .navigationBarHidden(isEditing).animation(.linear(duration: 0.25))
        }
    }
}

struct SearchBar: View {
    @Binding var text: String
    @Binding var isEditing: Bool
    
    init(text: Binding<String>, isEditing: Binding<Bool>) {
        self._text = text
        self._isEditing = isEditing
    }

    var body: some View {
        HStack {
            TextField("Search Country...", text: $text)
                .padding(7.5)
                .padding(.horizontal, 20)
                .background(Color(.systemGray6))
                .cornerRadius(7.5)
                .overlay(
                    HStack {
                        Image(systemName: "magnifyingglass")
                            .foregroundColor(.gray)
                            .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
                            .padding(.leading, 7.5)
                        
                        if isEditing && text.count != 0 {
                            Button(action: {
                                self.text = ""
                            }) {
                                Image(systemName: "multiply.circle.fill")
                                    .foregroundColor(.gray)
                                    .padding(.trailing, 7.5)
                            }
                        }
                    }
                )
                .padding(.horizontal, 10)
                .onTapGesture {
                    withAnimation {
                        self.isEditing = true
                    }
                }
            
            if isEditing {
                Button(action: {
                    withAnimation {
                        self.isEditing = false
                        self.text = ""
                    }
                    // Dismiss the keyboard
                    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                }) {
                    Text("Cancel")
                }
                .padding(.trailing, 10)
                .animation(.linear(duration: 0.25))
            }
        }
        
        .textCase(.none)
        .frame(height: 50)
        .padding(0)
        .background(
            GeometryReader { proxy in
                Color(UIColor.systemBackground)
                .frame(width: proxy.size.width * 1.3, height: 100).fixedSize()
                    .offset(CGSize(width: -20.0, height: -50.0))
        })
    }
}

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

React.js how to install get started, classes render html and JSX

React.js how to install get started, classes render html and JSX

React (also known as React.js or ReactJS) is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications.

1. C:\reactdev>npm install -g create-react-app
2. C:\reactdev>create-react-app myreactdev
3. C:\reactdev>cd myreactdev
4. C:\reactdev\myreactdev>npm start
5. http://localhost:3000/
reactdev\myreactdev\src\index.js
////C:\reactdev\myreactdev\src\index.js
import React from 'react';
import ReactDOM from 'react-dom';
//Render HTML
const myelement = (
    <table>
      <tr>
        <th>Name</th>
      </tr>
      <tr>
        <td>John</td>
      </tr>
      <tr>
        <td>Elsa</td>
      </tr>
    </table>
  );
  
  ReactDOM.render(myelement, document.getElementById('root'));
reactdev\myreactdev\src\index.js
//C:\reactdev\myreactdev\src\index.js
import React from 'react';
import ReactDOM from 'react-dom';
//JavaScript XML
const myelement = <input type="text" />;

ReactDOM.render(myelement, document.getElementById('root'));
reactdev\myreactdev\public\index.html
//C:\reactdev\myreactdev\public\index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
  </head>
  <body>

    <div id="root"></div>
</body>
</html>

SwiftUI Add Rows to List

SwiftUI Add Rows to List
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {

    @State private var locations = ["Olongapo", "Angeles", "Subic"]
    
    var body: some View {
        NavigationView {
            List {
                ForEach(locations, id: \.self) { location in
                    Text(location)
                }
            }
            .navigationBarTitle(Text("Locations"))
            .navigationBarItems(trailing: Button(action: {
                self.addRow()
            }) {
                Image(systemName: "plus")
            })
        }
    }
        
    private func addRow() {
        self.locations.append("New Location")
    }
}


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

SwiftUI Simple Calculator

SwiftUI Simple Calculator
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders on 7/30/21.
//

import SwiftUI

struct ContentView: View {
     
    @State private var firstNumber = 0
    @State private var secondNumber = 0
    @State private var operand = ""
    @State private var calculatorText = "0"
    @State private var isTypingNumber = false
     
    var body: some View {
        VStack(spacing: 30) {
            TextField("0", text: $calculatorText)
                .border(Color.white, width: 2)
                .padding()
                .multilineTextAlignment(.trailing)
                .foregroundColor(Color.white)
            HStack {
                createCalcDigit("1")
                    .modifier(CustomButton())
                Spacer()
                createCalcDigit("2")
                    .modifier(CustomButton())
                Spacer()
                createCalcDigit("3")
                    .modifier(CustomButton())
            }
            .padding()
            .foregroundColor(Color.white)
 
            HStack {
                createCalcDigit("4")
                    .modifier(CustomButton())
                Spacer()
                createCalcDigit("5")
                    .modifier(CustomButton())
                Spacer()
                createCalcDigit("6")
                    .modifier(CustomButton())
            }
            .padding()
            .foregroundColor(Color.white)
             
            HStack {
                createCalcDigit("7")
                    .modifier(CustomButton())
                Spacer()
                createCalcDigit("8")
                    .modifier(CustomButton())
                Spacer()
                createCalcDigit("9")
                    .modifier(CustomButton())
            }
            .padding()
            .foregroundColor(Color.white)
             
            HStack {
                Button(action: {
                    self.operandTapped("-")
                }) {
                    (Text("-"))
                }
                .modifier(CustomButton(buttonbackgroundColor: Color.gray))
                 
                Spacer()
                createCalcDigit("0")
                    .frame(width: 70, height: 70)
                    .foregroundColor(Color.white)
                    .background(Color.orange)
                    .clipShape(Circle())
                Spacer()
                Button(action: {
                    self.operandTapped("+")
                }) {
                    (Text("+"))
                }
                .modifier(CustomButton(buttonbackgroundColor: Color.gray))
            }
            .padding()
            .foregroundColor(Color.white)
             
            HStack {
                Spacer()
 
                Button(action: {
                    self.calculate()
                }) {
                    (Text("="))
                }
                .modifier(CustomButton(buttonbackgroundColor: Color.gray))
                Spacer()
            }
            .foregroundColor(Color.white)
        }
        .font(.largeTitle)
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.black)
        .ignoresSafeArea()
    }
     
    private func createCalcDigit(_ number: String) -> Button<Text> {
        return Button(action: {
            self.digitTapped(number)
        }) {
            (Text(number))
        }
    }
 
    private func digitTapped(_ number: String) -> Void {
        if isTypingNumber {
            calculatorText += number
        } else {
            calculatorText = number
            isTypingNumber = true
        }
    }
 
    private func operandTapped(_ operand: String) {
        isTypingNumber = false
        firstNumber = Int(calculatorText)!
        self.operand = operand
        calculatorText = operand
    }
 
    private func calculate() {
        isTypingNumber = false
        var result  = 0
        secondNumber = Int(calculatorText)!
 
        if operand == "+" {
            result = firstNumber + secondNumber
        } else if operand == "-" {
            result = firstNumber - secondNumber
        }
 
        calculatorText = "\(result)"
    }
}

struct CustomButton: ViewModifier {
     
    var buttonbackgroundColor = Color.orange
    
    func body(content: Content) -> some View {
        return content
            .frame(width: 70, height: 70)
            .foregroundColor(Color.white)
            .background(buttonbackgroundColor)
            .clipShape(Circle())
    }
}

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

SwiftUI Context Menu

SwiftUI Context Menu
The ContextMenu modifier will display a menu with items.
ContentView.swift
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        HStack {
            Text("Action - Long-press") //Long-press the action button to display the context menu.
                .font(.title)
                .contextMenu {
                    Button(action: {}) {
                        Text("Share")
                        Image(systemName: "square.and.arrow.up")
                    }
                    Button(action: {}) {
                        Image(systemName: "heart.fill")
                        Text("Favorite")
                    }
            }
        }
    }
}


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

Tuesday, August 10, 2021

SwiftUI Fetch JSON Data into List

SwiftUI Fetch JSON Data into List
In this tutorial a list of todo items will be fetched and displayed in a List. url https://jsonplaceholder.typicode.com/todos

JSON
[
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
},
{
"userId": 1,
"id": 3,
"title": "fugiat veniam minus",
"completed": false
},
etc.
ContentView.swift
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @ObservedObject var fetch = FetchToDo()
    
    var body: some View {
        VStack {
            List(fetch.todos) { todo in
                VStack(alignment: .leading) {
                    Text(todo.title)
                    Text("\(todo.completed.description)") // print boolean
                        .font(.system(size: 11))
                        .foregroundColor(Color.gray)
                }
            }
        }
    }
}

class FetchToDo: ObservableObject {
  @Published var todos = [Todo]()
     
    init() {
        let url = URL(string: "https://jsonplaceholder.typicode.com/todos")!
        URLSession.shared.dataTask(with: url) {(data, response, error) in
            do {
                if let todoData = data {
                    let decodedData = try JSONDecoder().decode([Todo].self, from: todoData)
                    DispatchQueue.main.async {
                        self.todos = decodedData
                    }
                } else {
                    print("No data")
                }
            } catch {
                print("Error")
            }
        }.resume()
    }
}

struct Todo: Codable, Identifiable {
    public var id: Int
    public var title: String
    public var completed: Bool
}

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

SwiftUI Delete Multiple Rows from List

SwiftUI Delete Multiple Rows from List
A simple Delete multiple rows The selected items will be removed in the live preview.
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI


struct ContentView: View {
    
    @State var numbers = ["Record1","Record2","Record3","Record4","Record5","Record6","Record1Seven","Record1Eight","Record1Nine","Record1Ten"]
    @State var editMode = EditMode.inactive
    @State var selection = Set<String>()
    
    var body: some View {
        NavigationView {
            List(selection: $selection) {
                ForEach(numbers, id: \.self) { number in
                    Text(number)
                }
            }
            .navigationBarItems(leading: deleteButton, trailing: editButton)
            .environment(\.editMode, self.$editMode)
        }
    }
    private var editButton: some View {
        if editMode == .inactive {
            return Button(action: {
                self.editMode = .active
                self.selection = Set<String>()
            }) {
                Text("Edit")
            }
        }
        else {
            return Button(action: {
                self.editMode = .inactive
                self.selection = Set<String>()
            }) {
                Text("Done")
            }
        }
    }
    
    private var deleteButton: some View {
        if editMode == .inactive {
            return Button(action: {}) {
                Image(systemName: "")
            }
        } else {
            return Button(action: deleteNumbers) {
                Image(systemName: "trash")
            }
        }
    }
    
    private func deleteNumbers() {
        for id in selection {
            if let index = numbers.lastIndex(where: { $0 == id })  {
                numbers.remove(at: index)
            }
        }
        selection = Set<String>()
    }
}


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

SwiftUI TextEditor How to set Placeholder and background

SwiftUI TextEditor How to set Placeholder and background
ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    @State private var text = ""
   var body: some View {
       NavigationView {
               VStack(alignment: .leading){
                   Text("How are you feeing today?")
                       .font(.title)
                   CustomTextEditor.init(placeholder: "Start typing..", text: $text)
                       .font(.body)
                       .background(Color(UIColor.systemGray6))
                       .accentColor(.green)
                       .frame(height: 400)
                       .cornerRadius(8)
                   Spacer()
               }.padding()
   
           .navigationTitle("Navigation")
       }
   }
}

struct CustomTextEditor: View {
    let placeholder: String
    @Binding var text: String
    let internalPadding: CGFloat = 5
    var body: some View {
        ZStack(alignment: .topLeading) {
            if text.isEmpty  {
                Text(placeholder)
                    .foregroundColor(Color.primary.opacity(0.25))
                    .padding(EdgeInsets(top: 7, leading: 4, bottom: 0, trailing: 0))
                    .padding(internalPadding)
            }
            TextEditor(text: $text)
                .padding(internalPadding)
        }.onAppear() {
            UITextView.appearance().backgroundColor = .clear
        }.onDisappear() {
            UITextView.appearance().backgroundColor = nil
        }
    }
}

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

Related Post