似たような質問があるのですが、回答までたどり着けないので質問させてください。
共通パーツを作って、ViewControllerで制御したいのですができません。
ViewControllerにはUIViewを配置していて、そこに共通パーツのCustomViewを配置したいです。
現在、以下のようなコードを記載しています。
(1)共通パーツ「testView(xib,swift)」製作
・testView.xib作成
Xcodeにて、File->New->File->UserInterfaceよりViewを選択しUILabelを配置
・testView.swift作成
Xcodeにて、File->New->File->CocoaTouchClassのSubclassにUIViewで"testView"作成し以下のコードを記載
・XcodeにてtestView.xibのFile'sOwnerにtestViewを設定
・XcodeにてtestView.xibにUILabelを配置し、ドラッグドロップでtestView.swiftにIBOutletを設定
swift
1import UIKit 2class testView: UIView { 3 @IBOutlet weak var testLabel: UILabel! 4 // コードから生成された場合の初期化 5 override init(frame: CGRect){ 6 super.init(frame: frame) 7 loadNib() 8 } 9 // ストーリーボードから生成された場合の初期化 10 required init(coder aDecoder: NSCoder) { 11 super.init(coder: aDecoder)! 12 loadNib() 13 } 14 func loadNib(){ 15 // Xibのファイル名? 16 let view = Bundle.main.loadNibNamed("testView", owner: self, options: nil)?.first as! UIView 17 view.frame = self.bounds 18 self.addSubview(view) 19 } 20}
(2)testMainViewController(ViewController)を作成し、以下に記述
Xcodeにて、File->New->File->CocoaTouchClassのSubclassにUIViewControllerで"testMainViewController"を作成し以下のコードを記載
・XcodeのStoryBoadにてViewControllerにclassにtestMainViewControllerを設定
UILabelを配置
・xcodeで配置したUILabelのclassにtestViewを設定
・XcodeのStoryBoadにてUILabelをドラッグドロップでtestMainViewController.swiftにIBOutletを設定[testViewParent]
swift
1import UIKit 2class testMainViewController: UIViewController { 3 @IBOutlet weak var testViewParent: testView! 4 override func viewDidLoad() { 5 super.viewDidLoad() 6 testViewChild = UINib(nibName: "testView", bundle: nil).instantiate(withOwner: self, options: nil).first as? testView 7 addSubviewWithAutoLayout(childView: testViewChild!, parentView: testViewParent) 8 } 9 // 親viewに対してフルで表示するためのautolayoutの制約 10 private func addSubviewWithAutoLayout(childView: UIView, parentView: UIView) { 11 parentView.addSubview(childView) 12 parentView.addConstraint(NSLayoutConstraint(item: childView, attribute: .top, relatedBy: .equal, toItem: parentView, attribute: .top, multiplier: 1.0, constant: 0)) 13 parentView.addConstraint(NSLayoutConstraint(item: childView, attribute: .right, relatedBy: .equal, toItem: parentView, attribute: .right, multiplier: 1.0, constant: 0)) 14 parentView.addConstraint(NSLayoutConstraint(item: childView, attribute: .bottom, relatedBy: .equal, toItem: parentView, attribute: .bottom, multiplier: 1.0, constant: 0)) 15 parentView.addConstraint(NSLayoutConstraint(item: childView, attribute: .left, relatedBy: .equal, toItem: parentView, attribute: .left, multiplier: 1.0, constant: 0)) 16 } 17 override func didReceiveMemoryWarning() { 18 super.didReceiveMemoryWarning() 19 } 20}
回答2件
あなたの回答
tips
プレビュー