UICollectionViewのカスタムセルの表示を変更(更新)する方法を知りたい
カスタムセルが、漢字変換の候補のように、一列に表示されます。
表示ボタンを押し、作成関数InsertTextで文字を入力し、それに合わせた候補を呼び込むために、セルの内容やセル数を更新したいんですが、文字が入力されたら、強制的に作成関数serchTextで、候補を読み直したのち、そのデータでセルを強制的に更新したいんです。
どうすれば、できるでしょうか?
import UIKit
import RealmSwift
import Foundation
class dic: Object {
dynamic var ID = 0
dynamic var yomi = ""
dynamic var Kigou = ""
dynamic var date = NSDate(timeIntervalSince1970: 1)
override static func primaryKey() -> String? {
return "ID"
}
}
class KeyboardViewController: UIInputViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet var nextKeyboardButton: UIButton!
private var lexicon: UILexicon!
var myCollectionView : UICollectionView!
var button11: UIButton!
var button12: UIButton!
var fFastBoot = true
var fPri = CGFloat(20)
var ifontSize = 18.0
var RPath = ""
var sTextNum: Int = 0
var sTexst: String = "12345"
var cellNum: Int = 0
var tText:String = ""
var sText:String = ""
var listYomi: [String] = [];
var listKigou: [String] = [];
var listDate: [NSDate] = [];
var layout = UICollectionViewFlowLayout()
// Portrait表示におけるキーボードの高さ
private var portraitHeight: CGFloat = 190.0
private var portraitWidth: CGFloat!
// Landscape表示におけるキーボードの高さ
private var landscapeHeight: CGFloat = 100.0
private var landscapeWidth: CGFloat!
override func updateViewConstraints() {
super.updateViewConstraints()
// Add custom view sizing constraints here
}
var realmPath: String {
let containerURL = NSFileManager().containerURLForSecurityApplicationGroupIdentifier("group.AppGroupKigouKeybora")
return containerURL!.URLByAppendingPathComponent("Dictionary.realm").path!
}
override func viewDidLoad() {
super.viewDidLoad()
let pas = realmPath
print(pas)
// Perform custom UI setup here
self.nextKeyboardButton = UIButton(type: .System)
self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), forState: .Normal)
self.nextKeyboardButton.sizeToFit()
self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false
self.nextKeyboardButton.addTarget(self, action: "advanceToNextInputMode", forControlEvents: .TouchUpInside)
self.view.addSubview(self.nextKeyboardButton)
let nextKeyboardButtonLeftSideConstraint = NSLayoutConstraint(item: self.nextKeyboardButton, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0)
let nextKeyboardButtonBottomConstraint = NSLayoutConstraint(item: self.nextKeyboardButton, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
self.view.addConstraints([nextKeyboardButtonLeftSideConstraint, nextKeyboardButtonBottomConstraint])
// CollectionViewのレイアウトを生成.
let layout = UICollectionViewFlowLayout()
// サイズの設定
layout.itemSize.height = 10
layout.itemSize.width = 10
// Cell一つ一つの大きさ.
layout.itemSize = CGSizeMake(25, 25)
// Cellのマージン.
layout.sectionInset = UIEdgeInsetsMake(2, 2, 2, 2)
// セクション毎のヘッダーサイズ.
layout.headerReferenceSize = CGSizeMake(0,0)
// 横スクロール
layout.scrollDirection = .Horizontal //.Vertical
// CollectionViewを生成.
myCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
myCollectionView.frame.size.height = 30
myCollectionView.frame.size.width = 100
myCollectionView.frame.offset(dx: 2, dy: 2)
myCollectionView.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0)
myCollectionView.delegate = self
print(myCollectionView.delegate)
myCollectionView.dataSource = self
print(myCollectionView.dataSource)
// Cellに使われるクラスを登録.
myCollectionView.registerClass(CustomUICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
myCollectionView.sizeToFit()
print(myCollectionView.frame)
view.addSubview(myCollectionView)
serchText("(")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let heightConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0, constant: 500)
view.addConstraint(heightConstraint)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
override func viewDidLayoutSubviews() {
var myNativeBoundSize: CGSize = UIScreen.mainScreen().bounds.size
let myNativeBoundSizeStrW: CGFloat = myNativeBoundSize.width
let myNativeBoundSizeStrH: CGFloat = myNativeBoundSize.height
var myWidth = myNativeBoundSize.width
var myHeight = myNativeBoundSize.height
// 向きの判定.
if isLandscape() { // Landscapeだったら、
let orientation = "Landscape"
// Landscape用の viewを表示する。
//print(orientation)
} else { // Portraitだったら、
let orientation = "Portrait"
// Portrait用の viewを表示する。
//print(orientation)
}
var sKishu = "iPad"
if String(self.view.bounds.size) == "(320.0, 330.0)" {
// iPhone, iPod touch
sKishu = "iPhone"
myWidth = 30
}else if String(self.view.bounds.size) == "(768.0, 500.0)" {
myCollectionView.frame.size.width = 764
}else if String(self.view.bounds.size) == "(1024.0, 500.0)" {
myCollectionView.frame.size.width = 1020
}
print(String(self.view.bounds.size))
//print(sKishu)
if CGFloat(myNativeBoundSizeStrH) == CGFloat(1024.0){
myWidth = myNativeBoundSizeStrW / CGFloat(13)
myHeight = myNativeBoundSizeStrH / CGFloat(20)
//print("iPad縦")
}else if CGFloat(myNativeBoundSizeStrH) == CGFloat(768.0){
myWidth = myNativeBoundSizeStrW / CGFloat(13)
myHeight = myNativeBoundSizeStrH / CGFloat(11)
//print("iPad横")
}else{
myWidth = myNativeBoundSizeStrW / CGFloat(10)
myHeight = myNativeBoundSizeStrH / CGFloat(10)
//print("Non")
}
if fFastBoot == false {
self.button11.frame = CGRectMake(0,3 + fPri, myWidth - CGFloat(2) ,myHeight - CGFloat(6))
self.button12.frame = CGRectMake(myWidth, 3 + fPri, myWidth - CGFloat(2), myHeight - CGFloat(6))
}else{
self.button11 = UIButton(type: .System)
self.button11 = UIButton(frame: CGRectMake(0, 3 + fPri, myWidth - CGFloat(2) ,myHeight - CGFloat(6)))
self.button11.setTitleColor(UIColor.blackColor(), forState: .Normal)
self.button11.addTarget(self, action: "btnUp11:", forControlEvents:.TouchUpInside)
self.button11.addTarget(self, action: "btnDown11:", forControlEvents:.TouchDown)
self.button12 = UIButton(type: .System)
self.button12 = UIButton(frame: CGRectMake(myWidth, 3 + fPri, myWidth - CGFloat(2), myHeight - CGFloat(6)))
self.button12.setTitleColor(UIColor.blackColor(), forState: .Normal)
self.button12.addTarget(self, action: "btnUp12:", forControlEvents:.TouchUpInside)
self.button12.addTarget(self, action: "btnDown12:", forControlEvents:.TouchDown)
}
self.button11.setTitle(NSLocalizedString(String(myNativeBoundSizeStrH), comment: "("), forState: .Normal)
self.button12.setTitle(NSLocalizedString(String(myNativeBoundSizeStrW), comment: ")"), forState: .Normal)
if fFastBoot == true {
self.button11.titleLabel?.font = UIFont.systemFontOfSize(CGFloat(ifontSize))
self.button12.titleLabel?.font = UIFont.systemFontOfSize(CGFloat(ifontSize))
self.view.addSubview(self.button11)
self.view.addSubview(self.button12)
fFastBoot = false
}
}
func btnDown11(sender: UIButton){
//fDub = false
self.button11.backgroundColor = UIColor.blackColor()
}
func btnUp11(sender: AnyObject){
self.button11.backgroundColor = UIColor.whiteColor()
let tText = ")"
InsertText(tText)
}
func InsertText (str: String){
tText = ""
sTextNum = sTextNum + 1
sText = sText + str
let proxy = textDocumentProxy
proxy.insertText(str)
serchText(str)
}
private func isWidth() -> CGFloat {
// 現時点で Landscape表示が適当かどうかを判断する。
let screenSize = UIScreen.mainScreen().bounds.size
let screenW = self.view.bounds.size.width
return screenW
}
private func isLandscape() -> Bool {
// 現時点で Landscape表示が適当かどうかを判断する。
let screenSize = UIScreen.mainScreen().bounds.size
let screenH = screenSize.height
let screenW = screenSize.width
let isLandscapeNow = !(self.view.frame.size.width ==
screenW * ((screenW < screenH) ? 1 : 0) +
screenH * ((screenW > screenH) ? 1 : 0))
return isLandscapeNow
}
override func textWillChange(textInput: UITextInput?) {
// The app is about to change the document's contents. Perform any preparation here.
}
override func textDidChange(textInput: UITextInput?) {
// The app has just changed the document's contents, the document context has been updated.
var textColor: UIColor
let proxy = self.textDocumentProxy
if proxy.keyboardAppearance == UIKeyboardAppearance.Dark {
textColor = UIColor.whiteColor()
} else {
textColor = UIColor.blackColor()
}
self.nextKeyboardButton.setTitleColor(textColor, forState: .Normal)
}
// セルの幅自動修正
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var size: CGSize = listKanji[indexPath.row].sizeWithAttributes([NSFontAttributeName: UIFont.systemFontOfSize(20.0)])
print(CGSizeMake(size.width + 20.0, 25))
return CGSizeMake(size.width + 20.0, 25) //self.flowLayout.itemSize.height)
}
/*
Cellが選択された際に呼び出される
*/
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("Num: \(indexPath.row)")
print(listKigou[indexPath.row])
}
/*
Cellの総数を返す
*/
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(cellNum)
return cellNum
}
/*
Cellに値を設定する
*/
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell : CustomUICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as! CustomUICollectionViewCell
//cell.textLabel?.text = indexPath.row.description
print(indexPath.row)
cell.textLabel?.text = listKigou[indexPath.row]
return cell
}
func serchText(inputText: NSString){
let realm = try! Realm(path: realmPath)
let results = realm.objects(dic).filter("yomi BEGINSWITH %@", inputText).sorted("date", ascending: false)
cellNum = 0
for result in results {
print(result.kanji)
listYomi = listYomi + [result.yomi]
listKigou = listKigou + [result.kigou]
listDate = listDate + [result.date]
cellNum = cellNum + 1
}
if cellNum == 0{
}else{
cellNum = cellNum - 1
}
}
}
class CustomUICollectionViewCell : UICollectionViewCell{
var textLabel : UILabel?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
// UILabelを生成.
textLabel = UILabel(frame: CGRectMake(0, 0, frame.width, frame.height))
textLabel?.text = "nil"
textLabel?.backgroundColor = UIColor.whiteColor()
textLabel?.textAlignment = NSTextAlignment.Center
// Cellに追加.
self.contentView.addSubview(textLabel!)
}
}
class InputCandidate: NSObject {
var input: String?
}