I currently have a button and a text field, named offlineListing and productURLField respectively. I am trying to automatically input the text "N/A" into the productURLField once offlineListing has been selected by using the following syntax:
@IBOutlet weak var productURLField: UITextField!
@IBAction func offlineListing(_ sender: Any) {
let productURLField = "N/A"
}
However once the button is selected, nothing happens. Is there a reason as to why this isn't working properly?
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I have a UILabel called "itemOneURL" which reads a URL from an external database and adds the value to this label as a string. I've got a separate button called "viewItemOne" (using a working segue) which once selected, will take the contents of the "itemOneURL" URL and open this link using the default browser.
Here is the code I am currently using to segue the button and label.
@IBOutlet weak var itemOneURL: UILabel!
@IBAction func viewItemOne(_ sender: UIButton) {
let firstURL = itemOneURL as? String
UIApplication.shared.open(URL(string:"\(firstURL)")! as URL, options: [:], completionHandler: nil)
}
However, once I select this button on the UI my application doesn't do anything. Whereas when I use the following syntax elsewhere, it works and loads the URL?
UIApplication.shared.open(URL(string:"https://www.apple.com")! as URL, options: [:], completionHandler: nil) Is there something I am doing wrong which is currently causing the button to not perform any action once selected? If so, how can I rectify this and get it working please?
I am using the following syntax in a View Controller (using a Storyboard) to remove the second element of an array in a database.
@IBAction func deleteItemOne(_ sender: UIButton) {
if userId == user?.uid {
let group_array = document["product"] as? [String] ?? [""]
if (group_array.count) 1 {
document.reference.updateData([
"product": FieldValue.arrayRemove([group_array[1]])
])
self.viewDidLoad()
self.viewWillAppear(true)
}
}
}
Once the element of the array has been removed, I am using the following syntax to then reload the View Controller.
self.viewDidLoad()
self.viewWillAppear(true)
However after removal of the element, the View Controller doesn't reload as intended, and in-fact it doesn't end up doing anything.
This leads to my question, is there a simple Swift function / method that I can call to reload the View Controller upon completion?
I have a string - "productRaw" which I am splitting up to show in separate sectionData cells, whilst under the same "Item 1" cellData table view. This is the code I am using to split up the String and add each separate part to a separate sectionData cell.
let group_array = document["product"] as? [String] ?? [""]
let productName1 = group_array.first ?? "No data to display :("
let productRaw = "\(productName1)"
let componentsRaw = productRaw.components(separatedBy: ", ")
var product = [String: String]()
for component in componentsRaw {
let keyVal = component.components(separatedBy: ": ")
product[keyVal[0]] = keyVal[1]
}
if let productName = product["Product Name"], let listingPrice = product["Listing Price"], let briefDescription = product["A brief description"], let productURL = product["Product URL"], let activeUntil = product["Listing active until"] {
self.tableViewData = [cellData(opened: false, title: "Item 1", sectionData: [productName], [listingPrice], [briefDescription], [productURL], [activeUntil])]
}
Where I am declaring the individual cells I want to be shown for the first section - "Item 1", when I only use [productName] in my sectionData then this compiles without any issues.
However when I also add , [listingPrice], [briefDescription], [productURL], [activeUntil] to my sectionData I receive the following error for the [cellData(opened: syntax.
Extra arguments at positions #4, #5, #6, #7 in call
So my question is, why am I receiving the above error and what can I do to resolve it?
I am trying to incorporate some SwiftUI into my UIKit based iPhone application. I have a view controller in my Storyboard called ‘SellingNewsViewController’ with an associated “.swift” file. In this “SellingNewsViewController.swift" file, I am using the following code to try and create a UIHostingController to show the SwiftUI code I currently have in another file called “ContentView.swift”.
class SellingNewsViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let controller = UIHostingController(rootView: ContentView())
self.addChild(controller)
self.view.addSubview(controller.view)
controller.didMove(toParent: self)
}
And I have a SwiftUI file in this directory (the code I am trying to run) named ‘ContentView.swift’ which has the following Syntax:
import SwiftUI
import SwiftyJSON
import SDWebImageSwiftUI
import WebKit
struct ContentView: View {
@ObservedObject var list = getData()
var body: some View {
NavigationView{
List(list.datas){i in
NavigationLink(destination:
webView(url: i.url)
.navigationBarTitle("", displayMode: .inline)){
HStack(spacing: 15){
VStack(alignment: .leading, spacing: 10){
Text(i.title).fontWeight(.heavy)
Text(i.desc)
}
if i.image != "" {
WebImage(url: URL(string: i.image)!, options: .highPriority, context: nil)
.resizable()
.frame(width: 110, height: 135)
.cornerRadius(20).lineLimit(2)
}
}.padding(.vertical, 15)
}
}.navigationBarTitle("Headlines")
}
}
}
struct ChildHostingController_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct dataType : Identifiable {
var id : String
var title : String
var desc : String
var url : String
var image : String
}
class getData : ObservableObject{
@Published var datas = [dataType]()
init() {
let source = "https://newsapi.org/v2/top-headlines?country=gb&category=business&apiKey=mykeyishere"
let url = URL(string: source)!
let session = URLSession(configuration: .default)
session.dataTask(with: url) { (data, _, err) in
if err != nil{
print((err?.localizedDescription)!)
return
}
let json = try! JSON(data: data!)
for i in json["articles"] {
let title = i.1["title"].stringValue
let description = i.1["description"].stringValue
let url = i.1["url"].stringValue
let image = i.1["urlToImage"].stringValue
let id = i.1["publishedAt"].stringValue
DispatchQueue.main.async {
self.datas.append(dataType(id: id, title: title, desc: description, url: url, image: image))
}
}
}.resume()
}
}
struct webView : UIViewRepresentable {
var url : String
func makeUIView(context: UIViewRepresentableContextwebView) - WKWebView{
let view = WKWebView()
view.load(URLRequest(url: URL(string: url)!))
return view
}
func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContextwebView) {
}
}
I understand that I need to use a UIHostingController to show SwiftUI views in my UIKit application, however whenever I load up my ‘SellingNewsViewController’, I just receive a blank screen, as shown here - h ttps://imgur.com/a/GlyWV9i
Am I doing something wrong to try and create/show the UIHostingController?
Hi,
I'm super sorry if this is a silly question - I've literally only just gotten into swift and am learning! Basically, I'm making a Mac App where you select 'submit' from one page (Page A), and it opens up another page (page B). I need to be able to write code for page B but as it is in the same controller file as Page A I can't seem to merge the two together.
Here's my code:
import Cocoa
class ViewController: NSViewController {
	@IBOutlet weak var enternamehere: NSTextField!
@IBOutlet weak var welcomemessage: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBAction func submit(_ sender: Any) {
var name = enternamehere.stringValue
if name.isEmpty {
name = "person without a name"
}
let greeting = "Hello \(name)!"
welcomemessage.stringValue = greeting
}
}
// Here is where I guess I need to reference Page B?
I have included a link here - h ttps://i.imgur.com/lu2oEbu.png to a screenshot of my Xcode in case my question is confusing.
Thanks guys! :)
I am using the following Swift in a View Controller to adapt an existing UITextField to a date format.
@IBOutlet weak var productTimeRemainingField: UITextField!
private var datePicker: UIDatePicker?
override func viewDidLoad() {
super.viewDidLoad()
datePicker = UIDatePicker()
datePicker?.datePickerMode = .dateAndTime
datePicker?.addTarget(self, action: #selector(newProductViewController.dateChanged(datePicker:)), for: .valueChanged)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(newProductViewController.viewTapped(gestureRecognizer:)))
view.addGestureRecognizer(tapGesture)
productTimeRemainingField.inputView = datePicker
}
@objc func viewTapped(gestureRecognizer: UITapGestureRecognizer) {
view.endEditing(true)
}
@objc func dateChanged(datePicker: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy hh:mm:ss"
productTimeRemainingField.text = dateFormatter.string(from: datePicker.date)
view.endEditing(true)
if #available(iOS 13.4, *) {
datePicker.preferredDatePickerStyle = .compact
}
}
The above code is working, and allows me to select both a time and date, however when the field is selected, the section where a user selects the time and date is shown right at the bottom of the page, making it nearly impossible to properly make a selection. Does anyone have any idea why this is happening, and how I can fix this so it is shown in the centre of the View Controller (as with the majority of other apps - see here - (h ttps://i.stack.imgur.com/M0os7.png) for an example.
This is a screenshot (h ttps://imgur.com/a/OqKXcR7) as to how the date picker currently is appearing.
I am trying to hide a button called "itemOneDelete" when a label ("itemOneLabel") on my View Controller is empty, by using an 'if' loop to change the visibility of the button to "alpha = 0" by using the following code: }
However I am receiving the following error for the itemOneDelete.alpha = 0 line and I can't seem to fathom why.
Value of type '(UIButton) - ()' has no member 'alpha'
I have also tried replacing line three with the following syntax, however I received a similar error:
itemOneDelete.hidden = true
Value of type '(UIButton) - ()' has no member 'hidden'
Can anyone explain why I am getting this error and how to resolve it please?