SwiftUI New File and Passing a value - variables

I have a value as $freq being passed to a new SwiftUI file as frequencyValue, however the file called DipoleView is getting the error below.
This is in the ContentView:
HStack{
NavigationLink(destination: DipoleView(frequencyValue: $freq)) {
Text("Dipole")
.font(.title)
.fontWeight(.bold)
.foregroundColor(.white)
.frame(width: 150.00, height: 50.0)
.background(Color.green)
.cornerRadius(25)
.shadow(radius: 10.0)
.padding()
}
The code below is at the base of the other file called DipoleView and it requires some code concerning the passing of the variable from the ContentView..
#if DEBUG
struct DipoleView_Previews: PreviewProvider {
static var previews: some View {
**DipoleView(frequencyValue: <#Binding<String>#>)**
}
}
#endif
The above DipoleView(frequencyValue: <#Binding#>) I need to place some code here but I am not sure what it is suppose to be?
Hoping someone can help a Newby.
Cheers.

Since you're just trying to create a preview, you can use a constant binding:
#if DEBUG
struct DipoleView_Previews: PreviewProvider {
static var previews: some View {
DipoleView(frequencyValue: .constant("some frequency value"))
}
}
#endif
This makes the binding immutable in your preview, but you shouldn't really need a mutable binding when previewing in the canvas.

Related

Assigning QObject pointer works via assignment but not binding

I have something similar to the following code snippets. I am simplifying the code here for attempted brevity.
First, a subclass of QAbstractListModel with the following data() implementation, and Q_INVOKABLE get_thing() method, which returns a pointer to a QObject subclass, QML_thing:
QVariant data(QModelIndex& index, int role) {
const auto& thing = m_data.at(index.row()); // shared pointer to QML_thing
switch(role)
{
case Qt::DisplayRole:
return thing->name(); // this works
case WholeThingRole:
return QVariant::fromValue(QML_thing*>(thing.get());
}
}
QML_thing* getThing(int index) const
{
const thing = m_data.at(index); // shared pointer
return thing.get();
}
Next, I have a Repeater in a QML file that has this code:
Repeater {
id: repeater
model: thingModel
ThingDelegate {
thing: wholeThing // This calls the role, but ends up being null
}
onItemAdded {
item.thing = model.getThing(index) // this works, but 'breaks' the binding
}
}
My question is: why doesn't the thing: binding in QML work, but the thing = version does?

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")
}
}

SwiftUI OpenWeatherApi App show no content

Im new to swift development and I can't make myself pass through this. I run my app and by pressing the "action" button I see no change on my text which should be the current temperature. And It's giving me an error "nw_protocol_get_quic_image_block_invoke dlopen libquic failed"
My code:
struct ContentView: View {
#State var temp = Int()
func CallApi(){
let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=budapest&appid=#########################################")
URLSession.shared.dataTask(with: url!){data, response, error in
if let data = data {
if let DecodedData = try? JSONDecoder().decode(Api.self, from: data){
self.temp = DecodedData.main.temp
}
}
}.resume()
}
struct Api: Codable, Hashable{
var main: DataStructre
}
struct DataStructre: Codable, Hashable {
var temp: Int
}
var body: some View {
Text("\(temp)")
Button("Idojaras"){CallApi()}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
If you use do/try/catch instead of try?, you can get a useful error message.
do {
let DecodedData = try JSONDecoder().decode(Api.self, from: data)
self.temp = DecodedData.main.temp
} catch {
print(error)
}
In this case, I get:
Parsed JSON number <304.31> does not fit in Int.
Changing the type of temp (in both the #State variable and the DataStructre) fixes the issue.
In general, I'd recommend pasting your JSON into app.quicktype.io, which will give you generated models with the correct types/structures.
Slightly unrelated to your issue, but you may want to look into using dataTaskPublisher and Combine in SwiftUI rather than dataTask (https://developer.apple.com/documentation/foundation/urlsession/processing_url_session_data_task_results_with_combine). Also, function names in Swift are generally lowercased.

NavigationLink work on simulator but don't work on real device iPhone

I am new in SwiftUi and i try to run the code below.On simulator work well, but when try to run on real device (iPhone/iPad) work one time. The first time i can go to second view, but when i return with "
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView{
NavigationLink(destination: Text("Second view")) { Text("First view")}
}
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif

Is it possible to programatically create a xaml page?

I might write no sense on the next lines:
I tried to derive a struct named mainpage from winrt::Windows::UI::Xaml::Controls::Page and pass it to winrt::xaml_typename<>(), in "<>" is mainpage.
It will be understandable when you look at the code:
Point number 1 "(1)" is the mainpage.h file, is very short.
Point number 2 "(2)" is the App.cpp file, it only has the necessary.
//(1) mainpage.h
#pragma once
#include "pch.h"
struct mainpage : winrt::Windows::UI::Xaml::Controls::Page
{
mainpage() {
winrt::Windows::UI::Xaml::Controls::Button thebutton = winrt::Windows::UI::Xaml::Controls::Button();
thebutton.Click([&](const IInspectable& sender, const winrt::Windows::UI::Xaml::RoutedEventArgs& event_arg)
{
thebutton.Content(winrt::box_value(L"Clicked"));
});
}
};
//(2) App.cpp
#include "pch.h"
#include "mainpage.h"
struct App : winrt::Windows::UI::Xaml::ApplicationT<App>
{
void OnLaunched(const winrt::Windows::ApplicationModel::Activation::LaunchActivatedEventArgs& event_arg)
{
winrt::Windows::UI::Xaml::Controls::Frame root_frame{ nullptr };
winrt::Windows::UI::Xaml::UIElement content = winrt::Windows::UI::Xaml::Window::Current().Content();
if (content)
{
root_frame = content.try_as<winrt::Windows::UI::Xaml::Controls::Frame>();
}
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (root_frame == nullptr)
{
// Create a Frame to act as the navigation context and associate it with
// a SuspensionManager key
root_frame = winrt::Windows::UI::Xaml::Controls::Frame();
root_frame.NavigationFailed({ this, &App::OnNavigationFailed });
if (event_arg.PreviousExecutionState() == winrt::Windows::ApplicationModel::Activation::ApplicationExecutionState::Terminated)
{
// Restore the saved session state only when appropriate, scheduling the
// final launch steps after the restore is complete
}
if (event_arg.PrelaunchActivated() == false)
{
if (root_frame.Content() == nullptr)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
root_frame.Navigate(winrt::xaml_typename<mainpage>(), box_value(event_arg.Arguments()));
}
// Place the frame in the current Window
winrt::Windows::UI::Xaml::Window::Current().Content(root_frame);
// Ensure the current window is active
winrt::Windows::UI::Xaml::Window::Current().Activate();
}
}
else
{
if (event_arg.PrelaunchActivated() == false)
{
if (root_frame.Content() == nullptr)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
root_frame.Navigate(winrt::xaml_typename<mainpage>(), box_value(event_arg.Arguments()));
}
// Ensure the current window is active
winrt::Windows::UI::Xaml::Window::Current().Activate();
}
}
}
void App::OnNavigationFailed(const IInspectable&, const winrt::Windows::UI::Xaml::Navigation::NavigationFailedEventArgs& event_arg)
{
throw winrt::hresult_error(E_FAIL, winrt::hstring(L"Failed to load Page ") + event_arg.SourcePageType().Name);
}
};
int __stdcall wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) {
winrt::Windows::UI::Xaml::Application::Start([](auto &&) { winrt::make<App>(); });
}
If it is not possible, how can I properly create a page?
It is simple if you have installed the CppWinRT VSIX. Then create a "View model" and edit the files. You shouldn't derive the struct from the winrt::Windows::UI::Xaml::Controls::Page class because winrt::xaml_typename<> needs a WinRT class in <>.