В основном, у меня есть сценарий, в котором мне нужно показать быстрый пользовательский интерфейс, который содержит цвет фона и текстовое поле внизу, и оба они будут показаны в нижней части экрана. И я покажу этот ответ как текст над полем ввода.
Иногда текст будет большим, поэтому мне нужно динамически обновить высоту контейнера wift пользовательского интерфейса, чтобы полностью показать ответ. Слишком много вещей, но ничего не работает. Может ли кто -нибудь помочь
Вот мини -версия того, что я пытаюсь сделать в двух словах. < /P>
import UIKit
import SwiftUI
class ViewController: UIViewController {
private let tableView = UITableView()
private let floatingActionButton = UIButton(type: .system)
private var swiftUIHostingController: UIHostingController?
private var isSwiftUIViewVisible = false
private var heightConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
setupFloatingActionButton()
}
private func setupTableView() {
// Add table view to view hierarchy
view.addSubview(tableView)
// Set up constraints - pin to edges, respect top safe area
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
// Configure table view
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
private func setupFloatingActionButton() {
// Configure floating action button
floatingActionButton.setTitle("+", for: .normal)
floatingActionButton.titleLabel?.font = UIFont.systemFont(ofSize: 24, weight: .bold)
floatingActionButton.backgroundColor = .systemBlue
floatingActionButton.setTitleColor(.white, for: .normal)
floatingActionButton.layer.cornerRadius = 28
floatingActionButton.layer.shadowColor = UIColor.black.cgColor
floatingActionButton.layer.shadowOffset = CGSize(width: 0, height: 2)
floatingActionButton.layer.shadowOpacity = 0.3
floatingActionButton.layer.shadowRadius = 4
// Add to view and set constraints
view.addSubview(floatingActionButton)
floatingActionButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
floatingActionButton.widthAnchor.constraint(equalToConstant: 56),
floatingActionButton.heightAnchor.constraint(equalToConstant: 56),
floatingActionButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
floatingActionButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -16)
])
// Add action
floatingActionButton.addTarget(self, action: #selector(floatingActionButtonTapped), for: .touchUpInside)
}
@objc private func floatingActionButtonTapped() {
if isSwiftUIViewVisible {
hideSwiftUIView()
} else {
showSwiftUIView()
}
}
private func showSwiftUIView() {
let swiftUIView = SwiftUIView()
swiftUIHostingController = UIHostingController(rootView: swiftUIView)
guard let hostingController = swiftUIHostingController else { return }
addChild(hostingController)
view.addSubview(hostingController.view)
hostingController.view.backgroundColor = .yellow
hostingController.didMove(toParent: self)
// Set up constraints
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
heightConstraint = hostingController.view.heightAnchor.constraint(equalToConstant: 300)
NSLayoutConstraint.activate([
hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
heightConstraint!
])
// Add tap gesture to dismiss when tapping outside
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped))
tapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(tapGesture)
// Initial position (off-screen) - use constraint height for consistency
hostingController.view.transform = CGAffineTransform(translationX: 0, y: 300)
// Animate in
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut) {
hostingController.view.transform = .identity
}
isSwiftUIViewVisible = true
// Schedule height increase after 5 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
self.increaseSwiftUIViewHeight()
}
}
private func hideSwiftUIView() {
guard let hostingController = swiftUIHostingController,
let heightConstraint = heightConstraint else { return }
// Remove tap gesture recognizer
view.gestureRecognizers?.removeAll { $0 is UITapGestureRecognizer }
// Use current constraint height for consistent animation
let currentHeight = heightConstraint.constant
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn) {
hostingController.view.transform = CGAffineTransform(translationX: 0, y: currentHeight)
} completion: { _ in
hostingController.willMove(toParent: nil)
hostingController.view.removeFromSuperview()
hostingController.removeFromParent()
self.swiftUIHostingController = nil
self.heightConstraint = nil
}
isSwiftUIViewVisible = false
}
private func increaseSwiftUIViewHeight() {
guard let heightConstraint = heightConstraint, isSwiftUIViewVisible else { return }
// Animate height change from 300 to 400
heightConstraint.constant = 400
self.view.layoutIfNeeded()
}
@objc private func backgroundTapped(_ gesture: UITapGestureRecognizer) {
let location = gesture.location(in: view)
// Check if tap is outside the SwiftUI view
if let hostingController = swiftUIHostingController,
!hostingController.view.frame.contains(location) {
hideSwiftUIView()
}
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20 // You can change this number as needed
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "cell - \(indexPath.row)"
return cell
}
}
// MARK: - SwiftUI View
struct SwiftUIView: View {
@State private var inputText: String = ""
var body: some View {
VStack {
Spacer()
HStack {
TextField("Ask me anything about travel", text: $inputText)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.horizontal, 20)
}
}
.ignoresSafeArea(.all)
.background(Color.blue)
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... i-big-time
Увеличение высоты контроллера вида хостинго ⇐ IOS
Программируем под IOS
-
Anonymous
1758629678
Anonymous
В основном, у меня есть сценарий, в котором мне нужно показать быстрый пользовательский интерфейс, который содержит цвет фона и текстовое поле внизу, и оба они будут показаны в нижней части экрана. И я покажу этот ответ как текст над полем ввода.
Иногда текст будет большим, поэтому мне нужно динамически обновить высоту контейнера wift пользовательского интерфейса, чтобы полностью показать ответ. Слишком много вещей, но ничего не работает. Может ли кто -нибудь помочь
Вот мини -версия того, что я пытаюсь сделать в двух словах. < /P>
import UIKit
import SwiftUI
class ViewController: UIViewController {
private let tableView = UITableView()
private let floatingActionButton = UIButton(type: .system)
private var swiftUIHostingController: UIHostingController?
private var isSwiftUIViewVisible = false
private var heightConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
setupFloatingActionButton()
}
private func setupTableView() {
// Add table view to view hierarchy
view.addSubview(tableView)
// Set up constraints - pin to edges, respect top safe area
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
// Configure table view
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
private func setupFloatingActionButton() {
// Configure floating action button
floatingActionButton.setTitle("+", for: .normal)
floatingActionButton.titleLabel?.font = UIFont.systemFont(ofSize: 24, weight: .bold)
floatingActionButton.backgroundColor = .systemBlue
floatingActionButton.setTitleColor(.white, for: .normal)
floatingActionButton.layer.cornerRadius = 28
floatingActionButton.layer.shadowColor = UIColor.black.cgColor
floatingActionButton.layer.shadowOffset = CGSize(width: 0, height: 2)
floatingActionButton.layer.shadowOpacity = 0.3
floatingActionButton.layer.shadowRadius = 4
// Add to view and set constraints
view.addSubview(floatingActionButton)
floatingActionButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
floatingActionButton.widthAnchor.constraint(equalToConstant: 56),
floatingActionButton.heightAnchor.constraint(equalToConstant: 56),
floatingActionButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
floatingActionButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -16)
])
// Add action
floatingActionButton.addTarget(self, action: #selector(floatingActionButtonTapped), for: .touchUpInside)
}
@objc private func floatingActionButtonTapped() {
if isSwiftUIViewVisible {
hideSwiftUIView()
} else {
showSwiftUIView()
}
}
private func showSwiftUIView() {
let swiftUIView = SwiftUIView()
swiftUIHostingController = UIHostingController(rootView: swiftUIView)
guard let hostingController = swiftUIHostingController else { return }
addChild(hostingController)
view.addSubview(hostingController.view)
hostingController.view.backgroundColor = .yellow
hostingController.didMove(toParent: self)
// Set up constraints
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
heightConstraint = hostingController.view.heightAnchor.constraint(equalToConstant: 300)
NSLayoutConstraint.activate([
hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
heightConstraint!
])
// Add tap gesture to dismiss when tapping outside
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped))
tapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(tapGesture)
// Initial position (off-screen) - use constraint height for consistency
hostingController.view.transform = CGAffineTransform(translationX: 0, y: 300)
// Animate in
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut) {
hostingController.view.transform = .identity
}
isSwiftUIViewVisible = true
// Schedule height increase after 5 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
self.increaseSwiftUIViewHeight()
}
}
private func hideSwiftUIView() {
guard let hostingController = swiftUIHostingController,
let heightConstraint = heightConstraint else { return }
// Remove tap gesture recognizer
view.gestureRecognizers?.removeAll { $0 is UITapGestureRecognizer }
// Use current constraint height for consistent animation
let currentHeight = heightConstraint.constant
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn) {
hostingController.view.transform = CGAffineTransform(translationX: 0, y: currentHeight)
} completion: { _ in
hostingController.willMove(toParent: nil)
hostingController.view.removeFromSuperview()
hostingController.removeFromParent()
self.swiftUIHostingController = nil
self.heightConstraint = nil
}
isSwiftUIViewVisible = false
}
private func increaseSwiftUIViewHeight() {
guard let heightConstraint = heightConstraint, isSwiftUIViewVisible else { return }
// Animate height change from 300 to 400
heightConstraint.constant = 400
self.view.layoutIfNeeded()
}
@objc private func backgroundTapped(_ gesture: UITapGestureRecognizer) {
let location = gesture.location(in: view)
// Check if tap is outside the SwiftUI view
if let hostingController = swiftUIHostingController,
!hostingController.view.frame.contains(location) {
hideSwiftUIView()
}
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20 // You can change this number as needed
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "cell - \(indexPath.row)"
return cell
}
}
// MARK: - SwiftUI View
struct SwiftUIView: View {
@State private var inputText: String = ""
var body: some View {
VStack {
Spacer()
HStack {
TextField("Ask me anything about travel", text: $inputText)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.horizontal, 20)
}
}
.ignoresSafeArea(.all)
.background(Color.blue)
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79766907/increasing-height-of-hosting-view-controller-is-messing-up-swift-ui-big-time[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия