I need help I have these ColorSlider App that change the color of Square with 3 sliders RGB .I like to create a Tableview where i can store presets of color and retrieve from preset name e.g. Ocean Blue,
Emerald Green, Red Ferrary etc. I create The Tableview with the push of the button but I am stuck with the rest of implementation. Please I need help.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var redSlider: UISlider!
#IBOutlet weak var greenSlider: UISlider!
#IBOutlet weak var blueSlider: UISlider!
#IBOutlet weak var displaylbl: UILabel!
#IBOutlet weak var displayView: UIView!
var color:Color!
override func viewDidLoad() {
super.viewDidLoad()
color = Color(red: redSlider.value, green: greenSlider.value, blue: blueSlider.value)
displaylbl.text = color.getString()
displayView.backgroundColor = color.getColor()
}
#IBAction func sliderChanged(_ sender: UISlider) {
if (sender.tag == 1){
color.setRed(red: sender.value)
displaylbl.text = color.getString()
displayView.backgroundColor = color.getColor()
}
else if (sender.tag == 2) {
color.setGreen(green: sender.value)
displaylbl.text = color.getString()
displayView.backgroundColor = color.getColor()
}
else if (sender.tag == 3) {
color.setBlue(blue: sender.value)
displaylbl.text = color.getString()
displayView.backgroundColor = color.getColor()
}
}
}
import UIKit
class Color {
private var red:CGFloat
private var green:CGFloat
private var blue:CGFloat
init(red:Float, green:Float, blue:Float) {
self.red = CGFloat(red)
self.green = CGFloat(green)
self.blue = CGFloat(blue)
}
func setRed(red:Float) {
self.red = CGFloat(red)
}
func setGreen(green:Float) {
self.green = CGFloat(green)
}
func setBlue(blue:Float) {
self.blue = CGFloat(blue)
}
func getColor() -> UIColor {
let color = UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1.0)
return color
}
func getString() -> String {
let string = "Red: \(Int(round(red)))\nGreen: \(Int(round(green)))\nBlue: \(Int(round(blue)))"
return string
}
}
First you need to get the RGB color from slider and show in box, if you have done this part then now you need to do is whenever you are showing color in box you just make a dictionary with keys like :
let dict = [ colorName : "whatever you want",
colorCode : "Which you get from slider"
]
Add it in array too like:
arrayColor.append(dic)
Populate your tableview from arrayColor array, and in didselectatindexpath you need to get colorCode atIndexPath.row and set in box.
Hope this will help you. For any other query comment below.
Related
I have 4 Tab Bar Items. When these are clicked, I want a different website to open.
I tried the examples on the internet but couldn't get it to work. I want 4 different urls to be opened when 4 different buttons are pressed on a single page.
I can't seem to catch the click event. I check the logs with print but it is not responding.
Storyboard
My codes. Does it not respond when clicked?
//
// ViewController.swift
// Oto
//
// Created by Emre Taner Çetinkaya on 19.08.2022.
//
import UIKit
import WebKit
import Foundation
class ViewController: UIViewController, WKNavigationDelegate, UITabBarControllerDelegate {
#IBOutlet weak var tabBar: UITabBar!
#IBOutlet weak var profileButton: UITabBarItem!
#IBOutlet weak var discountButton: UITabBarItem!
#IBOutlet weak var urgencyButton: UITabBarItem!
#IBOutlet weak var homeButton: UITabBarItem!
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.delegate = self
setUpSetting();
loadData(link: "https://oto.com/")
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
let tabBarIndex = tabBarController.selectedIndex
switch tabBarIndex {
case 0:
loadData(link: "https://oto.com/")
print("press 0");
case 1:
loadData(link:"oto.com//sayfa/acil-acil/")
case 2:
loadData(link: "https://oto.com//sayfa/fiyati-dusenler/")
case 3:
loadData(link: "https://oto.com//sayfa/giris-yap/")
default:
loadData(link: "https://oto.com/")
}
}
}
func setUpSetting () {
let tabBarAppearance = UITabBarAppearance()
let tabBarItemAppearance = UITabBarItemAppearance()
tabBarItemAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
tabBarItemAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
tabBarAppearance.backgroundColor = hexStringToUIColor(hex: "3f475f")
tabBarAppearance.stackedLayoutAppearance = tabBarItemAppearance
tabBar.standardAppearance = tabBarAppearance
tabBar.scrollEdgeAppearance = tabBarAppearance
}
func hexStringToUIColor(hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
func loadData(link : String) {
let url = URL(string: link)!
webView.load(URLRequest(url: url))
webView.allowsBackForwardNavigationGestures = true
}
}
This question already has answers here:
How to initialize properties that depend on each other
(4 answers)
Closed 3 years ago.
I'm trying to follow along CS 193P course and I'm currently on a Lecture 2. The lector made var game = Concentration(numberOfPairsOfCards: cardButtons.count / 2) and it worked fine for him, however, it doesn't work at all for me. Am I missing something? I can't pass anything there.
Here's my ViewController class:
class ViewController: UIViewController {
#IBOutlet weak var flipCountLabel: UILabel!
#IBOutlet var cardButtons: [UIButton]!
var game = Concentration(numberOfPairsOfCards: cardButtons.count / 2)
var emojiChoices = ["🎃", "👻", "🎃", "👻"]
var flipCount = 0 {
didSet {
flipCountLabel.text = "Flips: \(flipCount)"
}
}
//MARK: - IBActions
#IBAction func touchCard(_ sender: UIButton) {
flipCount += 1
if let cardNumber = cardButtons.index(of: sender) {
flipCard(withEmoji: emojiChoices[cardNumber], on: sender)
}
}
//MARK: - Methods
func flipCard(withEmoji emoji: String, on button: UIButton) {
if button.currentTitle == emoji {
button.setTitle("", for: .normal)
button.backgroundColor = #colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)
} else {
button.setTitle(emoji, for: .normal)
button.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
}
}
And Concentration:
class Concentration {
var cards = [Card]()
func chooseCard(at index: Int) {
}
init(numberOfPairsOfCards: Int) {
for _ in 1...numberOfPairsOfCards {
let card = Card()
cards += [card, card]
}
//TODO: - Shuffle the cards
}
}
The error is
Cannot use instance member 'cardButtons' within property initializer;
property initializers run before 'self' is available
and auto completion doesn't work either
You need to make it a var
var game:Concentration!
then inside viewDidLoad
game = Concentration(numberOfPairsOfCards: cardButtons.count / 2)
OR make it a lazy var
lazy var game:Concentration = {
return Concentration(numberOfPairsOfCards:self.cardButtons.count / 2)
}()
I am struggling to get my head around Firebase Real-time Database and to have it playing nicely with Table View in my restaurant ordering app!
Before reading my code (please don't laugh), what I am hoping to get my TableView is able to do are
1) sort the requests by category (using value retrieved from the key "RequestItemCategory" which has Int value of 1, 2, 3)
2) add the new request to the tableview AND sort the requests again according to the category
3) remove completed food request from the tableview when the customer or employee tick "complete order" on another device which will trigger a change to the "RequestCompleted" key of the requested child on Firebase to "true")
The only things that I can achieve after hours of mucking around are
when app starts, the app loads the table and displays all the requests in the right order according to their category but even the requests that are tagged completed on the Firebase are still displayed.
new orders are added to the bottom of the list but not sort into a category.
What I tried
1) Tag .queryEqual(toValue: "false", childKey: "RequestCompleted") to try to filter out completed requests returns an empty table (not nil information)
2) I can use a button to clear the requestArray then calls retrieveRequest() again. This will refresh the table and all requests will be in the right order but I like to have it done automatically if possible. Also, this method will create another observer so I ended multiple identical orders added to the list...
3) using .value instead of .childAdded - returns nil and the app crashes - I think I need to use for loops but not sure how to do it.
Please help thanks!
Codes are:
Class object
class Request {
var name : String = ""
var requestItem : String = ""
var seat : String = ""
var requestCategory : String = ""
}
Cell.swift
import UIKit
class CustomCellTableViewCell: UITableViewCell {
#IBOutlet var requestText : UITextField!
#IBOutlet var nameText: UITextField!
#IBOutlet var seatNumberText: UITextField!
#IBOutlet var timerText: UITextField!
#IBOutlet var cellBackground : UIView!
#IBOutlet var cellCategoryView : UIView!
#IBOutlet var cellCategoryLabel : UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
ViewController.swift
import UIKit
import Firebase
import SVProgressHUD
class MainPageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
#IBOutlet weak var requestTableView: UITableView!
var requestArray : [Request] = [Request]()
override func viewDidLoad() {
super.viewDidLoad()
requestTableView.delegate = self
requestTableView.dataSource = self
requestTableView.register(UINib(nibName: "CustomCellTableViewCell", bundle: nil), forCellReuseIdentifier: "customRequestCell")
configureTableView()
retrieveRequest()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customRequestCell", for: indexPath) as! CustomCellTableViewCell
cell.nameText.text = requestArray[indexPath.row].name
cell.seatNumberText.text = requestArray[indexPath.row].seat
cell.requestText.text = requestArray[indexPath.row].requestItem
cell.cellCategoryLabel.text = requestArray [indexPath.row].requestCategory
if cell.cellCategoryLabel.text == "1" {
cell.cellBackground.backgroundColor = UIColor.init(red: 142/255, green: 0/255, blue: 0/255, alpha: 0.65)
} else if cell.cellCategoryLabel.text == "2" {
cell.cellBackground.backgroundColor = UIColor.init(red: 234/255, green: 179/255, blue: 0/255, alpha: 0.75)
} else {
cell.cellBackground.backgroundColor = UIColor.init(red: 0/255, green: 113/255, blue: 119/255, alpha: 0.65)
}
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return requestArray.count
}
func configureTableView() {
requestTableView.rowHeight = UITableView.automaticDimension
requestTableView.estimatedRowHeight = 73
}
func retrieveRequest() {
let ref = Database.database().reference().child(“Restaurant”).child("Requests").queryOrdered(byChild: "RequestItemCategory")**.queryEqual(toValue: "false", childKey: "RequestCompleted")** adding .queryEqual doesn't work...
ref.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as? [String : AnyObject] ?? [:]
let customerName = snapshotValue["Lastname"]
let customerSeatnumber = snapshotValue[“Seat”]
let customerRequestedItem = snapshotValue["RequestItem"]
let customerRequestedItemCategory = snapshotValue ["RequestItemCategory"]
let request = Request()
request.name = customerName as! String
request.seat = customerSeatnumber as! String
request.requestItem = customerRequestedItem as! String
request.requestCategory = "\(customerRequestedItemCategory!)"
self.requestArray.append(request)
self.configureTableView()
self.requestTableView.reloadData()
}
}
}
ps. the requestLabel.text is used to change the color of a particular UIView according to the category (RequestItemCategory)
I am following the standford ios class for Fall 2017. As the professor goes through the demo, I follow by inputting and running like he does. He shows how using lazy with a var allows one to use the UIButton count for variable initialization. When I add the lazy keyword, the error doesn't go away. Thinking it was maybe an xcode update related problem, I downloaded someone else's version of the project and that project doesn't have the issue. The code is below, any thoughts? :/
class ViewController: UIViewController {
lazy var game = ConcentrationModel(numberOfPairsOfCards: (cardButtons.count + 1) / 2)
//Could have had var flipCount: Int = 0
//But it is inferred
var flipCount = 0 {
didSet {
flipCountLabel.text = "Flips: \(flipCount)"
}
}
var emojiChoices = ["🎃","👻","👿","🎃","👻","👿"]
#IBOutlet var cardButtons: [UIButton]!
#IBOutlet weak var flipCountLabel: UILabel!
#IBAction func touchCard(_ sender: UIButton) {
flipCount += 1
if let cardNumber = cardButtons.index(of: sender) {
flipCard(withEmoji: emojiChoices[cardNumber], on: sender)
print("cardNumber = \(cardNumber)")
} else {
print("chosen card was not in cardButtons")
}
print("agh!!! a ghost")
}
func flipCard(withEmoji emoji: String, on button: UIButton) {
if button.currentTitle == emoji {
button.setTitle("", for: UIControlState.normal)
button.backgroundColor = #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1)
} else {
button.setTitle(emoji, for: UIControlState.normal)
button.backgroundColor = #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1)
}
}
}
To initialize a lazy property which depends on the value of another property you have to use the closure syntax
lazy var game : ConcentrationModel = {
return ConcentrationModel(numberOfPairsOfCards: (self.cardButtons.count + 1) / 2)
}()
I am trying to have the value of a slider on a certain view appear in a text box on a child view. But when the second view loads, it seems that the value of the slider is lost and set to nil. How would I preserve the value of that slider before the view changes in order to use the most recent value in the child view? Here is some relevant code (I want to set the textbox "redTextBox" to be the "changeRed" slider's value):
PARENT CLASS--------------------------------
class ViewController: UIViewController {
#IBOutlet weak var changeRed: UISlider!
#IBOutlet weak var changeGreen: UISlider!
#IBOutlet weak var changeBlue: UISlider!
var r: Float = 0
var g: Float = 0
var b: Float = 0
#IBAction func slideRed(sender: AnyObject) {
self.view.backgroundColor = UIColor(colorLiteralRed: changeRed.value, green: changeGreen.value, blue: changeBlue.value, alpha: 1.0)
r = changeRed.value
g = changeGreen.value
b = changeBlue.value
}
#IBAction func slideGreen(sender: AnyObject) {
self.view.backgroundColor = UIColor(colorLiteralRed: changeRed.value, green: changeGreen.value, blue: changeBlue.value, alpha: 1.0)
r = changeRed.value
g = changeGreen.value
b = changeBlue.value
}
#IBAction func slideBlue(sender: AnyObject) {
self.view.backgroundColor = UIColor(colorLiteralRed: changeRed.value, green: changeGreen.value, blue: changeBlue.value, alpha: 1.0)
r = changeRed.value
g = changeGreen.value
b = changeBlue.value
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor(colorLiteralRed: changeRed.value, green: changeGreen.value, blue: changeBlue.value, alpha: 1.0)
}
......
}
CHILD CLASS----------------------------
class ColorValueVC: ViewController {
#IBOutlet weak var redTextBox: UITextField!
#IBOutlet weak var greenTextBox: UITextField!
#IBOutlet weak var blueTextBox: UITextField!
override func viewDidLoad() {
//super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
redTextBox.text = "\(changeRed.value)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Your child inherits from the parent view controller. What are you trying to achieve by doing this? If they're two view controllers where one segues to the other, then there should not be an inheritance link between them. Instead you pass data from A to B by implementing prepareForSegue in A.