UINavigtion controller back button do not show properly [closed] - ios11

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Native back buttons are buggy on iOS 11 as shown in the picture. Is there a solution for this?

Can you try this code to solve that. Leace the comment below if it not work for you.
var backImage = UIImage(named: "back_button_image").withRenderingMode(.alwaysOriginal)
let leftPadding: CGFloat = 10
let adjustSizeForBetterHorizontalAlignment: CGSize = CGSize(width: backImage.size.width + leftPadding, height: backImage.size.height)
UIGraphicsBeginImageContextWithOptions(adjustSizeForBetterHorizontalAlignment, false, 0)
backImage.draw(at: CGPoint(x: leftPadding, y: 0))
backImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.navigationController?.navigationBar.backIndicatorImage = backImage
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = backImage
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)

Related

How do I fill an array of data with CoreData data?

I am learning to use SwiftUI with Core Data.
I am trying to fill a Line Chart with saved weight data like below:
LineView(data: [0, 32, 445, 56, 99])
I’ve gotten as far as this but im getting an error on the "var locations = ..." line saying "Type of expression is ambiguous without more context"
var fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "UserWeight")
var locations = mocW.executeFetchRequest(fetchRequest, error: nil) as [UserWeight]
for weight in weights {
print(weights.userWeight)
}
Any help on this and how i would populate the line chart with this data would be greatly appreciated!
For SwiftUI, I suspect that you are attempting to achieve the following...
struct YourView: View {
#FetchRequest(entity: UserWeight.entity(),
sortDescriptors: []
) var weights: FetchedResults<UserWeight>
var body: some View {
ForEach(weights) { weight in
Text(weight.userWeight)
}
}
}
Core Data entities confirm to the Identifiable protocol, so you'e able to drop the id: parameter in the ForEach structure...
ForEach(weights) { weight in
Otherwise you'd need to use...
ForEach(weights, id: \.self) { weight in
Note: As an aside, it would help us if you could provide more detail in your questions in the future. The more information you provide, the easier it is for the community to understand your issue and provide a suitable response. Remember that your question and our answers may not only help you, but also help others in the future as they visit the site looking for answers to their own problems.
How do I ask a good question?
if let appDelegate =
UIApplication.shared.delegate as? AppDelegate {
let managedObjectContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<Memory>(entityName: "Memory")
let sortDescriptor = NSSortDescriptor(key: "rating", ascending: false)
var predicate = NSPredicate(format: "mediaType == %#", "image")
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = [sortDescriptor]
do {
result = try managedObjectContext.fetch(fetchRequest)
} catch {
}
}
"result" is an array of, in my case, Memory objects which are instances of NSManagedObject. To access properties and populate views I do this:
for memory in result {
let value = memory.entityPropertyName
}
I think this should be enough to get your started, let me know if you have more questions.
If UserWeight is a subclass of NSManagedObject, you should declare your fetch request as
var fetchRequest = NSFetchRequest<UserWeight>(entityName: "UserWeight")
Or else as
let fetchRequest: NSFetchRequest<UserWeight> = UserWeight.fetchRequest()
Then you can use the fetch like this, and the type of locations will be Array<UserWeight>.
let locations = try context.fetch(fetchRequest)
I'm not sure where executeFetchRequest(fetchRequest, error: nil) comes from-- it's not a function defined by NSManagedObjectContext in Swift. It resembles the Objective-C version of the function, but in Swift it's different.

Xcode Quiz look-a-like app with question and answer

I am trying to create a quiz look-a-like app, where the person who holds the phone ask the question, and the other people answer. So there will be two Strings. One with question, and one with the answer. I have created the questions something like this:
var questions = ["Question1", "Question2", "Question3", "Question4", "Question5"]
var answers = ["Answer1", "Answer2", "Answer3", "Answer4", "Answer5"]
When the tap a button, a new question with correct answer pops up. I know how I can display a random string from questions, but how do I connect it to also display the correct answer?
Another option is to use a Dictionary, with the Question as the Key and the Answer as the Value:
let questions: [String : String] = [
"Question1" : "Answer1",
"Question2" : "Answer2",
"Question3" : "Answer3",
"Question4" : "Answer4",
"Question5" : "Answer5"
]
You can then get a random Question & Answer like this:
let randomQuestion = questions.randomElement()
Then access the Question and Answer Text:
let questionText = randomQuestion?.key ?? ""
let answerText = randomQuestion?.value ?? ""
In relation to your next question:
How can I make sure the same question does not show multiple times, and when there are no more questions
You can construct an Array from the Dictionary Keys like this. The keys will be unordered anyway, but you should shuffle them if you want to repeat.
You can then iterate through each question in the randomised Array:
Set your properties in viewDidLoad, not when the button is tapped.
let randomQuestions = questions.keys.shuffled()
var currentQuestionIndex = 0
#IBAction func newQuestionButton(_ sender: Any) {
guard currentQuestionIndex != questions.count else {
return
// or reset your questionIndex and reshuffle.
}
// This will give you the Question (and Key)
let question = randomQuestions[currentQuestionIndex]
// Use the Key to extract out the answer (value) from the Dictionary
let answer = questions[question] ?? ""
// Update your labels
questionLabel.text = question
answerLabel.text = answer
// Increment your question index
currentQuestionIndex += 1
}
You can simply zip together questions and answers and then call randomElement on the result. This will give you a Tuple containing a random question and its respective answer - assuming the indices of questions and answers are in sync.
var questions = ["Question1", "Question2", "Question3", "Question4", "Question5"]
var answers = ["Answer1", "Answer2", "Answer3", "Answer4", "Answer5"]
let questionsAndAnswers = Array(zip(questions, answers))
let randomQA = questionsAndAnswers.randomElement()
You could create a QuizItem type like. Since you always need them together it is good practice to tie them together in one element instead of having two arrays.
struct QuizItem {
var question: String
var answer: String
}
Then you create and array (or list) [QuizItem] and add all items you want. At last you simply take random element of the array.
Here is some pseudo code:
var quizList = [QuizItem]()
quizList.append(...) // add questions & answers
let randomIndex = randomIndex between 0 and quizList.length-1
let item = quizList[randomIndex]
questionLable.text = item.question
answereLabel.text = item.answere

How to enhance the run speed of a function loop? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am able to run the function below to find and replace a few cells at a specific Sheet and column, but I need to optimize the function so that I can reduce the completion time.
var r=ss.getDataRange();
var rws=r.getLastRow();
var j=8;
var i,a,find,repl;
function findReplace(find, repl, range) {
find="alpha";
repl="beta";
for (i=1;i<=rws;i++) {
a=r.getCell(i, j).getValue();
if (r.getCell(i,j).getFormula()) {continue;}
if (a==find) { r.getCell(i, j).setValue(repl);}
try {
a=a.replace(find,repl);
r.getCell(i, j).setValue(a);
}
catch (err) {continue;}
}
};
Any suggestions?
In the column "H", You want to replace the value of find to repl.
You want to replace the value of find to repl, when the value includes find and the value is the same with find.
You want to ignore the formulas.
You want to reduce the process cost.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Pattern 1:
In this pattern, the value is created in the loop, and the created value is put with setValues(). Before you use this script, please set the sheet name.
Modified script:
function findReplace() {
const find = "alpha";
const repl = "beta";
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var range = sheet.getRange(1, 8, sheet.getLastRow(), 1);
var values = range.getValues();
var formulas = range.getFormulas();
var v = values.reduce((ar, row, i) => {
row.forEach((col, j) => {
if (formulas[i][j] != "") {
ar.push([formulas[i][j]]);
} else if (col.includes(find)) {
ar.push([col.replace(find, repl)]);
} else {
ar.push([col]);
}
});
return ar;
}, []);
range.setValues(v);
}
Pattern 2:
In this pattern, TextFinder is used. Before you use this script, please set the sheet name.
Modified script:
function findReplace() {
const find = "alpha";
const repl = "beta";
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
sheet.getRange(1, 8, sheet.getLastRow(), 1).createTextFinder(find).replaceAllWith(repl);
}
Note:
Please enable V8.
References:
reduce()
setValues(values)
Class TextFinder
If I misunderstood your question and this was not the direction you want, I apologize.

AngularJS - Delete request not working correctly [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm trying to sort out this issue with my delete URL. Basically, I want it to repeat and delete the URL. I assumed it was a for loop issue and still do, but it doesn't seem to make any difference:
if (toDeleteValue.length > 0) {
var deleteRequest = {};
deleteRequest.values = toDeleteValue;
for (var i = 0; i < toDeleteValue.length; i++) {
var deleteUrl = "api/users/" + $scope.targetEntity.id + "/values?value=" + values;
$http.delete(deleteUrl)
.then(function(response) {
});
}
}
My url currently is this:
http://localhost:8080/api/users/1/values?value=dwqdwq,wegergem
I would like to change it from one, to two instead depending how many entities I would like to delete.
http://localhost:8080/api/users/1/values?value=dwqdwq
http://localhost:8080/api/users/1/values?value=wegergem
seems like you're trying to delete each value 1 at a time...which is problematic in itself...
but instead of this
var deleteUrl = "api/users/" + $scope.targetEntity.id + "/values?value=" + values;
you need this
var deleteUrl = "api/users/" + $scope.targetEntity.id + "/values?value=" + toDeleteValue[i];
In my opinion, a better solution would be to add a new call that would accept an array of values and only make 1 call to delete instead of looping.

Split array of dictionay to subarrays of dictionary [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have array of dictionary
var array: [[String:AnyObject]]!
This array contains data like this:
[["timestamp" : 1462803636436 , "name" , "tttt" , ...... ],["timestamp" : 1526999236 , "name" , "aaaa" , ...... ]]
I want to split this array to subarrays by day :
Array 1 : today
[["timestamp" : "", .....],["timestamp" : "", ......]],....
Array 2 : yesterday
[["timestamp" : "", .....],["timestamp" : "", ......]],....
........
Thanks,
Make a [NSDateComponent : [[String:AnyObject]]] that maps each day to an array of maps belonging to that day.
Iterate over your array.
Get the day of each Dictionary (see this guide for details), and add it to the appropriate day's array in the new Dictionary.
let dayMapping : [NSDateComponent : [[String:AnyObject]]] = []
for submap in array {
let day = getDay(submap["timestamp"])
let dayArray = dayMapping[day]
if dayArray == nil { //if there's no array for this day yet
dayArray = []
dayMappying[day] = dayArray
}
dayArray.append(submap)
}
The implementation of "getDay" will take me longer, I'll take a look at it tonight.

Resources