So I have a stack view and the profile image needs to go next to the the username and stay there. How do I do that in this arranged stack view without conflicts because I have tried to anchor it to the top. Like this but no results:
But I am actually getting:
Here is the code for the stack view:
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(profileImageView)
contentView.addSubview(profileNameLabel)
contentView.addSubview(userHandel)
profileImageView.setContentHuggingPriority(.defaultHigh, for: .horizontal)
let innerPostStackView = UIStackView(arrangedSubviews: [profileNameLabel, userHandel, postTextLabel])
innerPostStackView.axis = .vertical
let postStackView = UIStackView(arrangedSubviews: [profileImageView, innerPostStackView])
postStackView.translatesAutoresizingMaskIntoConstraints = false
postStackView.alignment = .center
postStackView.spacing = 10
contentView.addSubview(postStackView)
NSLayoutConstraint.activate([
postStackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10),
postStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15),
postStackView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
postTextLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -15)
])
Hope someone can help.
Post
Replies
Boosts
Views
Activity
Hi,
Please see my View Controller as this just shows a white screen:
class ViewController: UIViewController {
enum Section {
case main
}
var collectionView: UICollectionView! = nil
var dataSource: UICollectionViewDiffableDataSource<Section,Product>?
var products: [Product] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationItem.title = "Products"
Task {
do {
await loadProducts()
}
}
//Uncomment when needed
configureHierarchy()
configureDataSource()
//collectionView.register(ListCell.self, forCellWithReuseIdentifier: "ListCell")
}
func loadProducts() async {
products = await APIService().listProducts()
}
func configure<T: SelfConfiguringCell>(with product: Product, for indexPath: IndexPath) -> T {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ListCell", for: indexPath) as? T else {
fatalError("Unable to dequeue Cell")
}
cell.configure(with: product)
return cell
}
}
extension ViewController {
private func createLayout() -> UICollectionViewLayout {
let config = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
return UICollectionViewCompositionalLayout.list(using: config)
}
}
extension ViewController {
private func configureHierarchy() {
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout())
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.backgroundColor = .white
view.addSubview(collectionView)
collectionView.delegate = self
}
private func configureDataSource() {
let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Product> { (cell, indexPath, product) in
var content = cell.defaultContentConfiguration()
content.text = "\(product.name)"
cell.contentConfiguration = content
}
dataSource = UICollectionViewDiffableDataSource<Section, Product>(collectionView: collectionView) {
(collectionView: UICollectionView, indexPath: IndexPath, identifier: Product) -> UICollectionViewCell? in
return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: identifier)
}
//inital data
var snapshot = NSDiffableDataSourceSnapshot<Section, Product>()
snapshot.appendSections([.main])
//Problem loading this information
snapshot.appendItems(products, toSection: .main)
dataSource?.apply(snapshot, animatingDifferences: false)
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
}
}
Best,
Imran
Hi,
So I basically want to load data from an remote API and I have set all the files up etc but I am having trouble on the data snapshot part of the collection view to load the products as a list view.
Please see the code below.
import UIKit
class ViewController: UIViewController {
enum Section {
case main
}
var collectionView: UICollectionView!
var dataSource: UICollectionViewDiffableDataSource<Section,Product>?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationItem.title = "Products"
// configureHierarchy()
//configureDataSource()
collectionView.register(ListCell.self, forCellWithReuseIdentifier: "ListCell")
}
func configure<T: SelfConfiguringCell>(with product: Product, for indexPath: IndexPath) -> T {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ListCell", for: indexPath) as? T else {
fatalError("Unable to dequeue Cell")
}
cell.configure(with: product)
return cell
}
}
extension ViewController {
private func createLayout() -> UICollectionViewLayout {
let config = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
return UICollectionViewCompositionalLayout.list(using: config)
}
}
extension ViewController {
private func configureHierarchy() {
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout())
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(collectionView)
collectionView.delegate = self
}
private func configureDataSource() {
let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Product> { (cell, indexPath, product) in
var content = cell.defaultContentConfiguration()
content.text = "\(product.name)"
cell.contentConfiguration = content
}
dataSource = UICollectionViewDiffableDataSource<Section, Product>(collectionView: collectionView) {
(collectionView: UICollectionView, indexPath: IndexPath, identifier: Product) -> UICollectionViewCell? in
return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: identifier)
}
//inital data
var snapshot = NSDiffableDataSourceSnapshot<Section, Product>()
snapshot.appendSections([.main])
snapshot.appendItems([Product], toSection: .main)
dataSource?.apply(snapshot, animatingDifferences: false)
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
}
}
My API doesn't have separate sections hence why I used an enum to define one but where am I going wrong appending items to the section?
Best,
Imran
Hi,
I am trying to code this is in UIKit but the problem I am having with compositional layout because I seriously do not understand it. I basically am going to put the images on the genres from the Assets I upload to Xcode. When clicked that will link to a Playlists View which will display playlists from the Apple Music API and then each playlist will link to a PlaylistDetailView which will show the playlist, Tracks inside of it and they can click to play it once again provided via Apple Music API.
The MiniPlayer View you see on the image that is a mini player just showing the current music playlist thumbnail and the track title and artist.
How the hell do I do this in UIKIt? I know I probs have to use compositional layout here but I am so confused how to call in the different files for the different view elements into the home view controller and then also how to build this out?
Best,
Imran
Hi,
Please see my code below:
` func configureRequestButton() {
let button = UIButton()
button.setTitle("Test", for: .normal)
button.setTitleColor(.systemBlue,for: .normal)
button.addTarget(self,
action: #selector(button), <---- need the fuction to execute here
for: .touchUpInside)
StackView.addArrangedSubview(button)
}
func requestMusicAuthorization() async throws {
let authorizationStatus = await MusicAuthorization.request()
if authorizationStatus == .authorized {
isAuthorizedForMusicKit = true
} else {
// User denied permission.
}
}````
So I need to basically call that request music authorisation function in that test button but every time I do it says you have to conform it to object c if I do it crashes the app. I have done the Plist stuff. I am using UIKIt programmatically coding the UI. Can someone help because most of the api docs is based for swifUI for music kit.
Hey,
I am trying to add new information I added to my JSONs to my Struct in SwiftUI but every time I do it then comes with an error that the struct doesn't conform to codable but when I remove it, it works?
Here is the struct:
struct Recipe: Identifiable, Codable {
let id: Int
let name: String
let creator: String
let serves: Int
let ingredients: [Ingredient]
let methods: [Method]
let imageURL: URL
enum CodingKeys: String, CodingKey {
case id, name, creator, serves, ingredients
case methods = "method"
case imageURL = "imageurl"
}
}
struct Ingredient: Codable {
let name: String
let quantity: Double
let measurement: String
}
struct Method: Codable {
let step: Int
let text: String
}
enum RecipeSelection: String, CaseIterable, Identifiable {
case vegan
case breakfast
case lunch
case dinner
var id: String { self.rawValue }
var name: String { self.rawValue.capitalized }
var menu: String {
switch self {
case .vegan: return "Vegan"
case .breakfast: return "Breakfast"
case .lunch: return "Lunch"
case .dinner: return "Dinner"
}
}
}
hope you can help.
best,
Imran
Hey,
I am trying to create something like this:
So far I have done this as I build up the Grid View:
So when you select the Image or Label under it should take you the respective View.
Hope you can help.
Best,
Imran
I am trying to basically get different blog posts from different blogs to show up in a feed like Apple news and then when you click on it it shows the blog post. However, the problem I am running into is this RSS isn't JSON so I cannot use it with URL session and decode that in the app. Even if I use a Zapier to Input new posts every time a new blog post happens for a blog, the posts won't show images. I would put that into Google sheet and then turn the sheet into a JSON to use inside the app but I would have to but the link to that JSON file into another Google Sheet which will hold the links to each JSON which then I can use in the App to Decode based on the coreML recommender output(something separate). But I am wanting to know A does this make any sense what I am doing? B. Is there a better way assuming I am using SwiftUI and I want to keep it simple to code so it doesn't get confusing.
Here is my current code:
import SwiftUI
struct ContentView: View {
@State private var title = randomEmojiImage.randomElement() ?? "👋"
@State private var titlePlace = Text("")
@State private var descript = Text("\(switching())")
func switching(){
if title == "👋" {
let titlePlace = Text("\(wave.Title)")
let descript = Text("\(wave.Description)")
} else if title == "✌️" {
let titlePlace = Text("\(peace.Title)")
let descript = Text("\(peace.Description)")
} else if title == "😀" {
let titlePlace = Text("\(happy.Title)")
let descript = Text("\(happy.Description)")
} else if title == "💩" {
let titlePlace = Text("\(****.Title)")
let descript = Text("\(****.Description)")
} else if title == "😢" {
let titlePlace = Text("\(sad.Title)")
let descript = Text("\(sad.Description)")
}
}
var body: some View {
VStack {
Text("\(title)")
.font(.system(size: 80))
.padding()
Text("\(titlePlace)")
.padding()
Text("\(descript)")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I am trying to get the title to switch from the arrays I have created for the emojis. but it keeps throwing an error when I interpolate the switching inside the text field? what is the correct way to do this?
FYI: Newbie.
Hi,
im trying to workout if using AV foundation media player to be able to add interactive video cards overlay during a video and then it continues where it left off?
im not sure but I’d assume that Fitness+ does the similar with live metrics but obviously this is slightly different because it’s interrupting the video to show an overlay of something interactive and then continuing video once finished.
Hello,
I have a big problem because I cannot ever seem to understand loops. The specific is how to use them effectively and how to use them overall. I sorta understand the syntax. I looked over the swift language guide and tried to practice on Code Academy but It won't get stuck in my head and I am so confused.
Imran
Hello,
I am looking to practice swift but I don't have Xcode due to my Macs Limitations (It's old and slow and it won't run Xcode, and I am not looking to upgrade until winter this year when Finger-crossed the New MacBooks Come or I'll take the iMac then) but I see Replit where I can practice the coding part but Nothing to do with Front-end like SwiftUI or UI building etc and then linking it too code.
Please can someone advice me on what to do using replit to write some code to continuously practice swift without XCODE due to my limitations.
Hi,
I want to add an RSS feed to my app that automatically updates when the app loads with new content from the RSS feed.
I am using SwiftUI right now, so How would I go about doing that?
Hi,
I completed the Apple App development book and I have read over the swift language guide, but I kinda feel like I know bits and bobs— like I don’t know where to go from here. I want to be able to create apps(obv) but I seriously don’t know how to plan it out and more importantly, How to continue learning new frameworks and swift?