How to switch textFieldStyle to a TextField when user taps the field? - textfield

I'm trying to change the TextField style from .plain to .roundedCorners when the user taps on the TextField.
The TextField itself is initially disabled (.plain style) and when the user taps on it, should enable editing mode (which is working) and change to (.roundedCorners style)
I've tried changing the style based on TextField state (if disabled ? .plain : .roundedCorners), but that doesn't seem to be working
.textFieldStyle(self.listState.editingScreenshot == nil ? .plain : .roundedCorners)
I get the following error when using inline if statement:
Type 'StaticMember' has no member
'roundedCorners'.

Using style conditionally may be challenging, I prefer this approach, which is also much more customizable:
In this example I use a darker border color depending on activation, and in the second example, I just remove the style completely:
struct ContentView: View {
#State private var active1: Bool = false
#State private var value1 = ""
#State private var active2: Bool = false
#State private var value2 = ""
var body: some View {
VStack(alignment: .leading) {
Spacer()
Text("Field 1")
TextField("", text: $value1, onEditingChanged: { self.active1 = $0 }).padding().overlay(TextFieldBorder(rounded: active1))
Text("Field 2")
TextField("", text: $value2, onEditingChanged: { self.active2 = $0 }).padding().overlay(TextFieldBorder(rounded: active2))
Spacer()
}.background(Color(white: 0.9))
}
}
struct TextFieldBorder: View {
var rounded = true
var body: some View {
Group {
if rounded {
RoundedRectangle(cornerRadius: 10).stroke(Color.black)
} else {
RoundedRectangle(cornerRadius: 10).stroke(Color.gray)
}
}
}
}
To remove the style completely:
struct TextFieldBorder: View {
var rounded = true
var body: some View {
Group {
if rounded {
RoundedRectangle(cornerRadius: 10).stroke(Color.black)
} else {
RoundedRectangle(cornerRadius: 10).stroke(Color.clear)
}
}
}
}

The static member you are looking for is roundedBorder:
public static var roundedBorder: RoundedBorderTextFieldStyle.Member { get }

Related

how to fetch data from API and set to the Image

This is my Model And I want to fetch data of publisherBanner and set
to the View But I can not set the image in view
import Foundation
public struct Banner: Decodable {
public let publisherBanners: [PublisherBanner]
public init(publisherBanners: [PublisherBanner]) {
self.publisherBanners = publisherBanners
}
}
public struct PublisherBanner: Decodable, Hashable {
public var id = UUID()
// public let bannerFor: String
// public let imageName: String
public let url: String
public init(url: String) {
self.url = url
}
}
This is my ViewModel
class BannerVM: ObservableObject {
#Published var datas = [PublisherBanner]()
let url = "apiUrlExample"
init() {
getData(url: url)
}
func getData(url: String) {
guard let url = URL(string: "\(url)") else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
if let data = data {
do {
let results = try JSONDecoder().decode(Banner.self, from: data)
DispatchQueue.main.async {
self.datas = results.publisherBanners
}
}
catch {
print(error)
}
}
}.resume()
}
}
And this is My View where I want to set Image
struct BannerView: View {
#StateObject var bannerObject = BannerVM()
var body: some View{
ScrollView(.horizontal,showsIndicators: false){
HStack(spacing:15) {
ForEach(bannerObject.datas, id: \.id){ item in
AsyncImage(url: URL(string: "\(item.url)")) { image in
image
.resizable().padding(4)
.frame(width: 150, height: 215)
} placeholder: {
Image("logo_gray").resizable().padding(1)
.frame(width: 150, height: 215)
}
}
}
}
.padding(8)
}
}
please help me for fetch the Image of My API
I am trying to fetch but i failed many times and please help me. And
thank you in advance.
Please read the error message you get
typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "publisherBanners", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))
It says that the value for key id in PublisherBanner is an Int, you have to declare
public struct PublisherBanner: Decodable, Hashable, Identifiable {
public let id: Int
public let url: URL
}
By the way you can decode the url directly to URL and the init method is for free.
And as PublisherBanner already conforms to Identifiable the code to load the image can be shortened to
ForEach(bannerObject.datas) { item in
AsyncImage(url: item.url) { image in
Another by the way is that String Interpolation in URL(string: "\(url)") is redundant because url is already a String. This is sufficient: URL(string: url)

SwiftUI : How I can set refreshable for my Scrollview without List

import SwiftUI
struct HomeView: View {
#StateObject var vm = NewsViewModel()
let dataService = NewsDataService.instance
init() {
dataService.apiCall(text: "Korea")
}
var body: some View {
NavigationView {
ScrollView(.vertical, showsIndicators: false) {
SearchView()
VStack {
Divider()
if let newsArray = vm.newsArray?.articles {
ForEach(newsArray) { news in
NewsRowView(news: news)
}
}
}
}
.navigationTitle("News")
.navigationBarTitleDisplayMode(.automatic)
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
Hi, I tried to find refresh for my scrollview.
But, most of the examples were capable with List.
As you can see my code, I makde my list with HStack children View.
Because of that, I can't use the ".refreshable" modifier.
So, I want to know how I can set that in my view.
And If I can, I want to see detailed code as well!
Thanks.
You could use refreshable like this in your NewsRowView. Keep in mind you would need to make sure you are using ObservableObject where necessary so that it will give you the new data once it's updated.
.refreshable {
Task {
let dataService = NewsDataService.instance
dataService.apiCall(text: "Korea")
}
}

Is there any way to bind a property to appConfig in tornadofx?

Suppose I want to save a view's height and width value using appConfig in tornadofx. Is there anyway I can bind these properties to appConfig, so that when I save the config, the latest value of height and width will always be saved?
If what you want to do is to save the current width/height of the Window and restore that when the View is docked again, you can override onDock to do both operations there:
override fun onDock() {
if (config["w"] != null && config["h"] != null) {
currentWindow?.apply {
width = config.double("w")!!
height = config.double("h")!!
}
}
currentWindow?.apply {
Bindings.add(widthProperty(), heightProperty()).onChange {
with (config) {
put("w", width.toString())
put("h", height.toString())
save()
}
}
}
}

Xamarin Forms Switch XAML

I'm new in Xamarin and i'm trying to create a simple page with some components.
One of these component is a Switch it works fine by itself but i would like to change the basic text "inactive/active" by "male/female"
I've seen that in Xaml for windows phone there is a ToggleSwitch Component with a On/OffContent property but i can't seems to find an equivalent in XAML for Xamarin Forms
any idea ?
Thank you!
The lack of built in switch options, or at least the lack of being able to rename the switch options, has been asked a few times.
You could go with custom renders, modify the text at the OS level or do like I chose to do, just build your own switch.
This switch is two buttons laid out horizontally with the text Yes and No. The selected button gets a red border, and the unselected a transparent border.
class CustomSwitch : Grid
{
public event EventHandler<SelectedItemChangedEventArgs> ItemSelected;
private Button negative;
private Button positive;
public static readonly BindableProperty SelectedItemProperty = BindableProperty.Create<CustomSwitch, Object>(t => t.SelectedItem, null, BindingMode.TwoWay, propertyChanged: OnSelectedItemChanged);
public CustomSwitch()
{
try
{
this.HorizontalOptions = LayoutOptions.Center;
this.VerticalOptions = LayoutOptions.Center;
negative = new Button();
negative.Text = "No";
negative.Style = <YourNameSpace>.AppStyling.Style_Button_Switch;
negative.Clicked += (o,s) => OnSelectedItemChanged(this, ItemSelected, (int)Classes.Collections.Enums.SelectionStatus.False);
positive = new Button();
positive.Text = "Yes";
positive.Style = <YourNameSpace>.AppStyling.Style_Button_Switch;
positive.Clicked += (o, s) => OnSelectedItemChanged(this, ItemSelected, (int)Classes.Collections.Enums.SelectionStatus.True);
this.Children.Add(negative, 0,0);
this.Children.Add(positive, 1,0);
}
catch(System.Exception ex)
{
<YourNameSpace>.Classes.Helpers.Helper_ErrorHandling.SendErrorToServer(ex, this.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name);
}
}
public Object SelectedItem
{
get
{
return base.GetValue(SelectedItemProperty);
}
set
{
if (SelectedItem != value)
{
base.SetValue(SelectedItemProperty, value);
InternalUpdateSelected();
}
}
}
private void InternalUpdateSelected()
{
if((int)SelectedItem == (int)Classes.Collections.Enums.SelectionStatus.False)
{
negative.BorderColor = <YourNameSpace>.AppStyling.Color_Selected;
positive.BorderColor = <YourNameSpace>.AppStyling.Color_UnSelected;
positive.Opacity = <YourNameSpace>.AppStyling.Opaque_High;
}
else if ((int)SelectedItem == (int)Classes.Collections.Enums.SelectionStatus.True)
{
negative.BorderColor = <YourNameSpace>.AppStyling.Color_UnSelected;
negative.Opacity = <YourNameSpace>.AppStyling.Opaque_High;
positive.BorderColor = <YourNameSpace>.AppStyling.Color_Selected;
}
else
{
negative.BorderColor = <YourNameSpace>.AppStyling.Color_UnSelected;
negative.Opacity = <YourNameSpace>.AppStyling.Opaque_High;
positive.BorderColor = <YourNameSpace>.AppStyling.Color_UnSelected;
positive.Opacity = <YourNameSpace>.AppStyling.Opaque_High;
}
}
private static void OnSelectedItemChanged(BindableObject bindable, object oldValue, object newValue)
{
CustomSwitch boundSwitch = (CustomSwitch)bindable;
if((int)newValue != (int)Classes.Collections.Enums.SelectionStatus.Unselected)
{
boundSwitch.SelectedItem = (int)newValue == (int)Classes.Collections.Enums.SelectionStatus.False ? (int)Classes.Collections.Enums.SelectionStatus.False : (int)Classes.Collections.Enums.SelectionStatus.True;
}
if (boundSwitch.ItemSelected != null)
{
boundSwitch.ItemSelected(boundSwitch, new SelectedItemChangedEventArgs(newValue));
}
boundSwitch.InternalUpdateSelected();
}
}

Windows Store Apps: animate control when visibility changes?

In my app I have A grid with visibility bound to a property in the view model.
What I want to do is when the visibility property changes at the view model, the grid fades in or out according to the visibility value: Visible/Collapsed.
how can I achieve this ?
Inspired by the answer of "HDW Production", here's the code for Windows Store and Windows Phone Store apps:
public class FadingVisibilityGrid : Grid
{
public static readonly DependencyProperty DeferredVisibilityProperty = DependencyProperty.Register(
"DeferredVisibility", typeof (Visibility), typeof (FadingVisibilityGrid), new PropertyMetadata(default(Visibility), DeferredVisibilityChanged));
private static void DeferredVisibilityChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var newVisibility = (Visibility)e.NewValue;
var grid = (FadingVisibilityGrid)sender;
var animation = new DoubleAnimation
{
Duration = new Duration(TimeSpan.FromMilliseconds(200))
};
Storyboard.SetTarget(animation, grid);
Storyboard.SetTargetProperty(animation, "Grid.Opacity");
grid.FadeStoryBoard.Stop();
grid.FadeStoryBoard = new Storyboard();
grid.FadeStoryBoard.Children.Add(animation);
if (newVisibility == Visibility.Visible)
{
animation.From = 0;
animation.To = 1;
grid.Visibility = Visibility.Visible;
grid.FadeStoryBoard.Begin();
}
else
{
animation.From = 1;
animation.To = 0;
grid.FadeStoryBoard.Completed += (o, o1) =>
{
grid.Visibility = newVisibility;
};
grid.FadeStoryBoard.Begin();
}
}
public Visibility DeferredVisibility
{
get { return (Visibility) GetValue(DeferredVisibilityProperty); }
set { SetValue(DeferredVisibilityProperty, value); }
}
private Storyboard _fadeStoryBoard = new Storyboard();
public Storyboard FadeStoryBoard
{
get { return _fadeStoryBoard; }
set { _fadeStoryBoard = value; }
}
}
You need a new DependencyProperty, either by inheriting from Grid and adding one or by creating an attached property. Let's call it DeferredVisibility and let it be of type Visibility.
When DeferredVisibility is changed to Visible, set the Visibility to Visible and animate the opacity from 0 to 1.
When DeferredVisibility is changed to Collapsed, animate the opacity from 1 to 0 and THEN set the Visibility to Collapsed.