Увеличение высоты контроллера вида хостингоIOS

Программируем под IOS
Ответить
Anonymous
 Увеличение высоты контроллера вида хостинго

Сообщение 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)
}
}


Подробнее здесь: https://stackoverflow.com/questions/797 ... i-big-time
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»