UILabelを複数個UIViewに乗せ、そのUIViewの長さに応じてUIScrollViewの長さを変えたいと思っています。
SizeToFitを使った方法はUIViewにもUIScrollViewにもあるようですが、
コードに書いても効果がありませんでした。
現時点でのコードでは縦にスクロールすることができません。
コードはこちらです。
swift
override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.navigationController?.setNavigationBarHidden(true, animated: false) var tokyoCount = 0 var tokyoArray = [0] // CSV読み込み if let csvPath = Bundle.main.path(forResource: "mise", ofType: "csv") { do { var csvString = try NSString(contentsOfFile: csvPath, encoding: String.Encoding.utf8.rawValue) as String csvString = csvString.replacingOccurrences(of: "\r\n", with: "") let array2:Array = csvString.components(separatedBy: ",") var items2 = [String]() array2.enumerated().forEach { (index, value) in items2.append(value) if value.range(of:string) != nil{ print("exists") tokyoArray.append(tokyoCount) } if (index + 1) % 6 == 0 { str2.append(items2) items2 = [String]() tokyoCount += 1 } } } catch { // エラー } } // ScrollViewを生成. myScrollView = UIScrollView() myScrollView.frame = CGRect(x: 10, y: 50, width: 300, height: self.view.frame.size.height) let myImageView = UIImageView() myImageView.frame = myScrollView.frame myImageView.contentMode = UIViewContentMode.scaleAspectFill myScrollView.addSubview(myImageView) myScrollView.backgroundColor = UIColor.gray myScrollView.alpha = 0.3 // Labelを作成. let label: UILabel = UILabel(frame: CGRect(x: 20, y: 10, width: 200, height: 30)) label.backgroundColor = UIColor.white label.layer.masksToBounds = true label.textColor = UIColor.black label.text = "店舗一覧" label.textAlignment = NSTextAlignment.center self.view.addSubview(label) let v:UIView = UIView(frame: CGRect(x: 10, y: 0, width: 300, height: 50)) v.backgroundColor = UIColor(red: 0.5, green: 1.0, blue: 0.3, alpha: 1.0); for var i in 1...tokyoArray.count-1{ //店名 let nameLabel: UILabel = UILabel(frame: CGRect(x: 20, y: 10+(i*100), width: 250, height: 50)) nameLabel.backgroundColor = UIColor.white nameLabel.numberOfLines = 0 nameLabel.textColor = UIColor.black nameLabel.tag = i nameLabel.text = str2[tokyoArray[i]][0] nameLabel.textAlignment = NSTextAlignment.left myScrollView.addSubview(nameLabel) //住所 let addressLabel: UILabel = UILabel(frame: CGRect(x: 20, y: 50+(i*100), width: 250, height: 50)) addressLabel.backgroundColor = UIColor.white addressLabel.numberOfLines = 0 addressLabel.textColor = UIColor.black addressLabel.tag = i addressLabel.text = str2[tokyoArray[i]][1] addressLabel.textAlignment = NSTextAlignment.left myScrollView.addSubview(addressLabel) } v.sizeToFit() myScrollView.sizeToFit() myScrollView.contentSize = CGSize(width:300, height:myScrollView.frame.size.height) self.view.addSubview(myScrollView) }
まだ回答がついていません
会員登録して回答してみよう