I got an issue when I tried to remove an item in a list. when I tried to remove a list it disappeared, but they show a new list. the case looks like this.
below I provided my code also
adapter.setOnItemClickedCallback(object : ListOrderAdapter.OnItemClickCallback {
override fun onDecrementButtonClicked(orderMenu: OrderMenu, itemView: View, position: Int) {
var quantityChanged = (orderMenu.quantity)!!.minus(1)
itemView.tv_order_number.text = quantityChanged.toString()
Log.e("Position", position.toString())
if (quantityChanged > 0) {
updateData(quantityChanged, orderMenu)
} else {
listItem.remove(orderMenu)
recyclerView.removeViewAt(position)
adapter.notifyItemRemoved(position)
adapter.notifyItemRangeRemoved(position, listItem.size)
Toast.makeText(applicationContext, "Pesanan telah di hapus dari orderan", Toast.LENGTH_SHORT).show()
}
}
})
}
private fun updateData(quantityChanged: Long, orderMenu: OrderMenu) {
for (item in listItem){
if (item.name.equals(orderMenu.name)){
item.quantity = quantityChanged
}
}
}
Related
I am trying to display the number of rows in a section in its header as shown below as COUNTHERE. The issue I'm running into is that I can't put any code inside the if statement that is not a view so I can't compute anything. Ideas?
struct Day1View: View {
var displayEmployees: [Employee]
var body: some View {
List {
Section(header: Text("Early (\(COUNTHERE)")) {
ForEach(displayEmployees) { employee in
if employee.shift == .early {
switch employee.post {
case .kitchen : Text(employee.name).foregroundColor(.blue)
case .floor : Text(employee.name).foregroundColor(.yellow)
case .upstairs : Text(employee.name).foregroundColor(.red)
case .greeting : Text(employee.name).foregroundColor(.green)
default : Text(employee.name).foregroundColor(.gray)
}
}
}
}
}
Since the section you showed is only for .early shift employees, you can get the count using a filtered version of the original array:
displayEmployees.filter({$0.shift == .early}).count
So your section becomes:
Section(header: Text("Early (\(displayEmployees.filter({$0.shift == .early}).count)")) {
Or, you can add a new computed property for the count:
var displayCount: Int {
return displayEmployees.filter({$0.shift == .early}).count
}
...
Section(header: Text("Early (\(displayCount)")) {
I have a TodoListView which displays a List in sections. The sections can be pending or completed as shown below. I am using Realm for my app. The problem is that how can I find out the task I want to delete, since they can belong in different sections.
What should I do in my onDelete function to delete the task in a particular section.
enum Sections: String, CaseIterable {
case pending = "Pending"
case completed = "Completed"
}
struct TodoListView: View {
#ObservedResults(Task.self) var tasks: Results<Task>
var pendingTasks: [Task] {
tasks.filter { $0.isCompleted == false }
}
var completedTasks: [Task] {
tasks.filter { $0.isCompleted == true }
}
var body: some View {
let _ = print(Self._printChanges())
List {
ForEach(Sections.allCases, id: \.self) { section in
Section {
let filteredTasks = section == .pending ? pendingTasks: completedTasks
if filteredTasks.isEmpty {
Text("No tasks")
}
ForEach(filteredTasks, id: \._id) { task in
HStack {
TaskCellView(task: task)
}
}.onDelete { indexSet in
// What to do here:
// can I get the element which I swiped to delete on
}
} header: {
Text(section.rawValue)
}
}
}.listStyle(.plain)
}
}
UPDATE:
I was able to write the following code and it seems to be working fine:
.onDelete { indexSet in
var filteredTasks: [Task] = []
switch section {
case .pending:
filteredTasks = tasks.filter { $0.isCompleted == false }
case .completed:
filteredTasks = tasks.filter { $0.isCompleted == true }
}
indexSet.forEach { index in
let task = filteredTasks[index]
$tasks.remove(task)
}
}
I am trying to make a numbered list out of the information the user inputs into a UITextView. For example,
List item one
List item two
List item three
Here is the code that I have tried but does not give me the desired effect.
var currentLine: Int = 1
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// Add "1" when the user starts typing into the text field
if (textView.text.isEmpty && !text.isEmpty) {
textView.text = "\(currentLine). "
currentLine += 1
}
else {
if text.isEmpty {
if textView.text.characters.count >= 4 {
let str = textView.text.substring(from:textView.text.index(textView.text.endIndex, offsetBy: -4))
if str.hasPrefix("\n") {
textView.text = String(textView.text.characters.dropLast(3))
currentLine -= 1
}
}
else if text.isEmpty && textView.text.characters.count == 3 {
textView.text = String(textView.text.characters.dropLast(3))
currentLine = 1
}
}
else {
let str = textView.text.substring(from:textView.text.index(textView.text.endIndex, offsetBy: -1))
if str == "\n" {
textView.text = "\(textView.text!)\(currentLine). "
currentLine += 1
}
}
}
return true
}
as suggested here: How to make auto numbering on UITextview when press return key in swift but had no success.
Any help is much appreciated.
You can subclass UITextView, override method willMove(toSuperview and add an observer for UITextViewTextDidChange with a selector that break up your text into lines enumerating and numbering it accordingly. Try like this:
class NumberedTextView: UITextView {
override func willMove(toSuperview newSuperview: UIView?) {
frame = newSuperview?.frame.insetBy(dx: 50, dy: 80) ?? frame
backgroundColor = .lightGray
NotificationCenter.default.addObserver(self, selector: #selector(textViewDidChange), name: .UITextViewTextDidChange, object: nil)
}
func textViewDidChange(notification: Notification) {
var lines: [String] = []
for (index, line) in text.components(separatedBy: .newlines).enumerated() {
if !line.hasPrefix("\(index.advanced(by: 1))") &&
!line.trimmingCharacters(in: .whitespaces).isEmpty {
lines.append("\(index.advanced(by: 1)). " + line)
} else {
lines.append(line)
}
}
text = lines.joined(separator: "\n")
// this prevents two empty lines at the bottom
if text.hasSuffix("\n\n") {
text = String(text.characters.dropLast())
}
}
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let textView = NumberedTextView()
view.addSubview(textView)
}
}
How do i create a Field value for a Particular Item in a Particular Language? I have an Excel that has all the item Names inside the RootItem .These Items exist in a en-US language Already. i need add values for a particular field for other languages.. Like en-GB, nl-NL, it-IT.
I have a List like
ItemName Language Translation
TestItem en-GB Hello
TestItem nl-NL Hallo
and so on..
The only problem is, when i do item.Add, it creates a new item rather than adding the value to the existing item. How can i handle this?
My code is as follows:
foreach (DataRow row in dt.Rows)
{
Language language = Language.Parse(languageId);
var rootItem = currentDatabase.GetItem(RootItemPath, language);
var item = rootItem.Add(itemName, templateItem);
if (item != null)
{
item.Fields.ReadAll();
item.Editing.BeginEdit();
try
{
//Add values for the fields
item.Fields["Translation"].Value = strTranslationValue;
}
catch (Exception)
{
item.Editing.EndEdit();
}
}
}
Try This:
var rootItem = currentDatabase.GetItem(RootItemPath);
foreach (DataRow row in dt.Rows)
{
Language language = Language.Parse(languageId);
var itemInCurrentLanguage = rootItem.Children.Where(i=>i.Name == itemName).FirstOrDefault();
if(itemInCurrentLanguage == null){
itemInCurrentLanguage = rootItem.Add(itemName, templateItem);
}
var itemInDestinationLanguage = currentDatabase.GetItem(itemInCurrentLanguage.ID, language );
if (itemInDestinationLanguage != null)
{
itemInDestinationLanguage.Fields.ReadAll();
itemInDestinationLanguage.Editing.BeginEdit();
try
{
//Add values for the fields
itemInDestinationLanguage.Fields["Translation"].Value = strTranslationValue;
}
catch (Exception)
{
//Log any error
}
finally
{
itemInDestinationLanguage.Editing.EndEdit();
}
}
}
You need to switch the language before you get the root item:
using (new LanguageSwitcher(language))
{
var rootItem = currentDatabase.GetItem(RootItemPath);
var item = rootItem.Add(selectedItem.Name, CommunityProjectTemplateId);
// Add new item here...
}
Does anyone know how to get a list of all the items protected (and unprotected them after) in sitecore?
I've googled around but I didn't find any relevant results.
Thanks in advance
This is what I have so far...
var homeItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath);
foreach (Item item in homeItem.Children)
{
if (item.Locking.IsLocked())
{
//to do
}
}
Unfortunately the item.Locking.IsLocked is not returning if the item is protected or not.
When you press protect or unprotect item this command is called:
item:togglereadonly
This is the part of the method who protect or unprotect item:
public override void Execute(CommandContext context)
{
if (context.Items.Length != 1)
return;
Item obj = context.Items[0];
obj.Editing.BeginEdit();
obj.Appearance.ReadOnly = !obj.Appearance.ReadOnly;
obj.Editing.EndEdit();
Log.Audit((object) this, "Toggle read only: {0}, value: {1}", AuditFormatter.FormatItem(obj), MainUtil.BoolToString(obj.Appearance.ReadOnly));
}
Found the solution
var homeItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath);
foreach (Item item in homeItem.Children)
{
if (item.Appearance.ReadOnly)
{
//stuff here
}
}
Cheers