カテゴリー
iOS Swift

UIView内でSwiftUIのViewを使用する

struct PlayController: View {
  var buttonSize:CGFloat = 32
  var body: some View {
    HStack(spacing: 30) {
      Button {
	
      } label: {
        Image(systemName: "stop.fill")
	  .resizable()
	  .frame(width: buttonSize, height: buttonSize)
      }
      Button {
				
      } label: {
        Image(systemName: "play.fill")
	  .resizable()
	  .frame(width: buttonSize, height: buttonSize)
      }
      Button {
			
      } label: {
        Image(systemName: "backward.end.fill")
	  .resizable()
	  .frame(width: buttonSize, height: buttonSize)
      }
      Button {
				
      } label: {
	Image(systemName: "forward.end.fill").resizable()
	  .resizable()
	  .frame(width: buttonSize, height: buttonSize)
      }
    }
  }
}
import UIKit
import SwiftUI

class ViewController: UIViewController {
	
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    view.backgroundColor = .red
    constrainControllers()
  }
	
  private func constrainControllers() {
    let controlSwiftUIView = PlayController()
    let controller = UIHostingController(rootView: controlSwiftUIView)
	    
    controller.view.translatesAutoresizingMaskIntoConstraints = false
      self.addChild(controller)
      self.view.addSubview(controller.view)
      controller.didMove(toParent: self)
      controller.view.heightAnchor.constraint(equalToConstant: 100).isActive = true
      controller.view.leadingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.leadingAnchor).isActive = true
      controller.view.trailingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.trailingAnchor).isActive = true
      controller.view.bottomAnchor.constraint(equalTo: self.view.layoutMarginsGuide.bottomAnchor).isActive = true
  }
}