I have some UIButtons that represents different Restaurants the content comes from a struct. In this struct is an Array with Tags for each Restaurant.
How can I hide a UIButton based on the Tags?
At the moment I have this in an provisionally way:
func filterFavorites() {
if importedDataA.filterTags.contains(filterPresetRestaurantTypeService) {
isVisibleA = true
} else {
isVisibleA = false
}
if importedDataB.filterTags.contains(filterPresetRestaurantTypeService) {
isVisibleB = true
} else {
isVisibleB = false
}
if importedDataC.filterTags.contains(filterPresetRestaurantTypeService) {
isVisibleC = true
} else {
isVisibleC = false
}
if importedDataD.filterTags.contains(filterPresetRestaurantTypeService) {
isVisibleD = true
} else {
isVisibleD = false
}
if importedDataE.filterTags.contains(filterPresetRestaurantTypeService) {
isVisibleE = true
} else {
isVisibleE = false
}
if importedDataF.filterTags.contains(filterPresetRestaurantTypeService) {
isVisibleF = true
} else {
isVisibleF = false
}
if importedDataG.filterTags.contains(filterPresetRestaurantTypeService) {
isVisibleG = true
} else {
isVisibleG = false
}
etc...
And...
func filterApply() {
if isVisibleA == true {
if UserDefaults.standard.bool(forKey: "hideFilteredObjects") == true {
cellA.isHidden = false
} else {
//cellA.popIn()
}
} else {
if UserDefaults.standard.bool(forKey: "hideFilteredObjects") == true {
cellA.isHidden = true
} else {
//cellA.popOut()
}
}
}
Instead of creating several instances of your struct importedDataA, importedDataB, importedDataC, etc., you can just create an array of instances something like:
var importedData: [your-structure] = []
Then instead of going through all of these items one by one with an if statement, you can use a for loop to go through these instances like:
for data in importedData{
if data.filterTags.contains(filterPresetRestaurantTypeService){
isVisibleG = true
} else {
isVisibleG = false
}
}
Assume you have a struct:
struct ImportedData{
var filterTags: [Int]
}
let buttons = [UIButton]() // add your buttons
let importedData = [ImportedData]() // add your importedData
(0..<(buttons.count)).map{buttons[$0].isHidden = UserDefaults.standard.bool(forKey: "hideFilteredObjects") && (!importedData[$0].filterTags.contains(filterPresetRestaurantTypeService))}
Related
I am adding in some functionalities for this iOS swift matching card game and I need to check if the first 2 buttons flipped over match. They have four types of emojis for eight cards, which means there are 4 pairs of matches. I am having trouble finding out how to check if the cards match and when they match, I need the background color of the buttons to opaque (invisible). Everything else works except the empty if statement in the concentration class within the chooseCard function. That is where I need help.
Here's all the code so you can see whats related to what:
class ViewController: UIViewController {
lazy var game = Concentration(numberOfPairsOfCards: (cardButtons.count + 1) / 2)
var flipCount = 0 {
// Property Observer
didSet { flipLabel.text = "Flips: \(flipCount)" }
}
#IBOutlet weak var flipLabel: UILabel!
#IBOutlet var cardButtons: [UIButton]!
#IBAction func touchCard(_ sender: UIButton) {
flipCount+=1
if let cardNumber = cardButtons.firstIndex(of: sender) {
game.chooseCard(at: cardNumber)
updateViewFromModel()
} else {
print ("chosen card was not in cardButtons")
}
}
var emojiChoices = ["👻", "🎃", "🙏🏾", "🦆"]
var emoji = [Int:String]()
func emoji(for card: Card) -> String {
if emoji[card.identifier] == nil, emojiChoices.count > 0 {
let randomIndex = Int(arc4random_uniform(UInt32(emojiChoices.count)))
emoji[card.identifier] = emojiChoices.remove(at: randomIndex)
}
return emoji[card.identifier] ?? "?"
}
func updateViewFromModel() {
for index in cardButtons.indices {
let button = cardButtons[index]
let card = game.cards[index]
if card.isFaceUp {
button.setTitle(emoji(for: card), for: UIControl.State.normal)
button.backgroundColor = UIColor.white
}
else {
button.setTitle("", for: UIControl.State.normal)
button.backgroundColor = UIColor.orange
}
}
}
}
import Foundation
class Concentration {
var cards = [Card]()
func chooseCard(at index: Int) {
if cards[index].isFaceUp {
cards[index].isFaceUp = false
}
else {
cards[index].isFaceUp = true
}
if cards[index].isFaceUp && cards[index].isMatched {
}
}
init(numberOfPairsOfCards: Int) {
for _ in 0..<numberOfPairsOfCards {
let card = Card()
cards += [card,card]
}
//TODO: Shuffle cards
cards.shuffle()
}
}
import Foundation
struct Card {
var isMatched = false
var isFaceUp = false
var identifier: Int
static var identifierFactory = 0
static func getUniqueIdentifier() -> Int {
Card.identifierFactory += 1
return Card.identifierFactory
}
init() {
self.identifier = Card.getUniqueIdentifier()
}
}
In your concentration class you will check for faceUp card indexes
Change your Concentration from class to Struct
struct Concentration { // instead of class Concentration
private var indexOfFaceUpCard: Int? {
get {
let faceUpCardIndices = cards.indices.filter { cards[$0].isFaceUp }
return faceUpCardIndices.count == 1 ? faceUpCardIndices.first : nil
} set {
for index in cards.indices {
cards[index].isFaceUp = (index == newValue)
}
}
}
Then you have mutating chooseCard method
mutating func chooseCard(at index: Int)
In your chooseCard method you check for matching
if !cards[index].isMatched {
if let matchIndex = indexOfFaceUpCard, matchIndex != index {
if cards[matchIndex] == cards[index] {
cards[matchIndex].isMatched = true
cards[index].isMatched = true
}
cards[index].isFaceUp = true
} else {
indexOfFaceUpCard = index
}
}
So your method look like this
mutating func chooseCard(at index: Int) {
if !cards[index].isMatched {
if let matchIndex = indexOfFaceUpCard, matchIndex != index {
if cards[matchIndex] == cards[index] {
cards[matchIndex].isMatched = true
cards[index].isMatched = true
}
cards[index].isFaceUp = true
} else {
indexOfFaceUpCard = index
}
}
}
Update your card struct
struct Card: Hashable {
var isMatched = false
var isFaceUp = false
var identifier: Int
static var identifierFactory = 0
static func getUniqueIdentifier() -> Int {
Card.identifierFactory += 1
return Card.identifierFactory
}
static func ==(lhs: Card, rhs: Card) -> Bool {
return lhs.identifier == rhs.identifier
}
init() {
self.identifier = Card.getUniqueIdentifier()
}
}
I am writing an application which tests your ability in Classical Greek. And I have a few View Controllers. In the test view controller, I have a huge Begin button, which when pressed initiates a sequence of code, as follows:
#IBAction func test(_ sender: Any) {
beginBtn.isHidden = true
beginBtn.isEnabled = false
answerOne.isHidden = false
answerTwo.isHidden = false
answerThree.isHidden = false
answerFour.isHidden = false
data.currentNumOQue = (data.qCQ + data.qWQ + data.qSQ)
if data.chooseCAlertDataLoaded == false {
data.chooseCharacterQuestionType.addAction(data.chooseCharacterQuestionTypeEngGrk)
data.chooseCharacterQuestionType.addAction(data.chooseCharacterQuestionTypeGrkEng)
data.chooseCAlertDataLoaded = true
} else {
print("not first question")
}
while data.currentQC <= data.qCQ {
present(data.chooseCharacterQuestionType, animated: false, completion: nil)
DispatchQueue.global(qos: .background).async {
while data.chooseCAlertReturnsEngGrk == nil {
}
DispatchQueue.main.sync {
if data.chooseCAlertReturnsEngGrk == true {
//Eng-Grk QUestion
data.chooseCAlertReturnsEngGrk = nil
} else {
//Grk=Eng QUestion
data.chooseCAlertReturnsEngGrk = nil
}
}
}
data.currentQC += 1
data.currentQ += 1
}
data.currentQC = 1
data.currentQW = 1
data.currentQS = 1
}
Can anyone help me in how to wait until the value chooseCAlertReturnsEngGrk is not nil and execute on, but not 'freezing' the UI when doing so?
Override didSet to call some function.. then in that callback function, do whatever you want with the parameter..
class DataSomething {
var chooseCAlertReturnsEngGrkObserver: ((_ newValue: SomeTime?) -> Void)?
var chooseCAlertReturnsEngGrk: SomeType? = nil {
didSet {
chooseCAlertReturnsEngGrkObserver?(chooseCAlertReturnsEngGrk)
}
}
}
I am trying to change the camera of the publisher in OpenTok. In Android it is super easy, but I don't understand how to do it in objective c for ios.
I tried :
if (_publisher.cameraPosition == AVCaptureDevicePositionFront)
{
_publisher.cameraPosition = AVCaptureDevicePositionBack; // back camera
} else
{
_publisher.cameraPosition = AVCaptureDevicePositionFront; // front camera
}
I have to say that I am a beginner in objective c (and in OpenTok).
How should I do?
Thank you :)
Try this one:
func setCameraPosition(_ position: AVCaptureDevicePosition) -> Bool {
guard let preset = captureSession?.sessionPreset else {
return false
}
let newVideoInput: AVCaptureDeviceInput? = {
do {
if position == AVCaptureDevicePosition.back {
return try AVCaptureDeviceInput.init(device: backFacingCamera())
} else if position == AVCaptureDevicePosition.front {
return try AVCaptureDeviceInput.init(device: frontFacingCamera())
} else {
return nil
}
} catch {
return nil
}
}()
guard let newInput = newVideoInput else {
return false
}
var success = true
captureQueue.sync {
captureSession?.beginConfiguration()
captureSession?.removeInput(videoInput)
if captureSession?.canAddInput(newInput) ?? false {
captureSession?.addInput(newInput)
videoInput = newInput
} else {
success = false
captureSession?.addInput(videoInput)
}
captureSession?.commitConfiguration()
}
if success {
capturePreset = preset
}
return success
}
func toggleCameraPosition() -> Bool {
guard hasMultipleCameras else {
return false
}
if videoInput?.device.position == .front {
return setCameraPosition(.back)
} else {
return setCameraPosition(.front)
}
}
For Swift 4
if(publisher.cameraPosition == .back)
{
publisher.cameraPosition = .front
}else{
publisher.cameraPosition = .back
}
I haven't checked for Objective C but it will be same like
I have been struggling with something for a while.
How can I return something in a nested if function?
The function below has the task of finding out if the userProfile has a verified card or not, if verified == 1 (true) then return true, else return false.
func userHasVerfifiedCard() -> Bool{
let userDocument = users.documentWithID(Meteor.userID!)
if let card = userDocument.valueForKey("profile")!["card"] {
print("has card")
if let verified = card!["verified"] as? Int {
print("card.verified as Int")
if verified == 1{
print("card.verified == 1")
lastFourCreditCardLbl.text = card!["last4"] as? String
return true
}else {
return false
}
}
}
your method won't return anything, if if let card won't work. But it must return a bool in any case.
func userHasVerfifiedCard() -> Bool {
let userDocument = users.documentWithID(Meteor.userID!)
if let card = userDocument.valueForKey("profile")!["card"] {
print("has card")
if let verified = card!["verified"] as? Int {
print("card.verified as Int")
if verified == 1 {
print("card.verified == 1")
lastFourCreditCardLbl.text = card!["last4"] as? String
return true
}
}
}
return false
}
Try this and let me know if it's helps..!
func userHasVerfifiedCard() -> Bool{
let userDocument = users.documentWithID(Meteor.userID!)
if let card = userDocument.valueForKey("profile")!["card"], verified = card!["verified"] as? Int where verified == 1 {
return true
} else {
return false
}
}
I want to check the array to see if all the fields have a value, and if all the fields have a value, then I want it to do something. My code does work but it is really messy. I'd like to know if there is an easier way of doing this.
#IBAction func testBtn(sender: AnyObject) {
self.textData = arrayCellsTextFields.valueForKey("text") as! [String]
for item in textData {
if item.isEmpty {
print("Missing")
switchKey = true
// alertviewer will go here
break
} else {
switchKey = false
}
}
if switchKey == false {
//navigation here
print("done")
}
}
You can do this with the filterfunction
if textData.filter({$0.isEmpty}).count > 0 {
// there is at least one empty item
} else {
// all items contain data
}
Try this combination of guard and .filter:
#IBAction func testBtn(sender: AnyObject) {
self.textData = arrayCellsTextFields.valueForKey("text") as! [String]
guard textData.count == (textData.filter { !$0.isEmpty }).count else {
print("Missing")
return
}
print("Done")
}