我有plist文件和数据库,在plist文件中有英文字母,在数据库行中有String例如(伦敦),我将String转换为characters数组并附加到plist文件中。我创建了14个UIButton(for循环),我从数据库行给出了setTitle,并给出了shuffle并添加了plist中的字母并给出了shuffle。
所以我的问题是从数据库中添加我的字符时只显示数据库中的字符并像这样洗牌:
但我不需要只需要首先添加setTitle数据库中的所有字符并进行洗牌,剩下的空按钮会从plist文件中添加如下:
我怎么能像上面的图片(第2张图片)那样做?!
这是我的代码,编写代码有什么问题? :
let fileName : String = " EnglishLetters"
let fileExt : String = "plist"
let pathRes = Bundle.main.path(forResource: fileName, ofType: fileExt)
let pathDict = NSDictionary(contentsOfFile: pathRes!)
var letters : [String] = pathDict?.object(forKey: "Letters") as! [String]
for data in listdata { // SQLite database
let dataAnswer = data.ans // ans is a row in the SQLite database
let dataArrayAnswer = dataAnswer.characters.map{String($0)}
letters.append(contentsOf: dataArrayAnswer)
for char in dataArrayAnswer {}
for i in 1...14 {
let tileButton = UIButton(type: .roundedRect)
let lettersAns = dataArrayAnswer.shuffled()[letters.distance(from: id, to: id)] // id is parameter
tileButton.setTitle(lettersAns, for: .normal)
tileButton.titleLabel?.font = UIFont(name: "HelveticaNeueW23forSKY-Bd", size: 15)
tileButton.setTitleColor(.black, for: .normal)
tileButton.setBackgroundImage(UIImage(named: "Cell"), for: .normal)
tileButton.addTarget(self, action: #selector(moveTile(sender:)), for: .touchUpInside)
xAxis = xAxis + buttonWidth + space
view.addSubview(tileButton)
if i%7 == 0 {
xAxis = emptySpace / 2
yAxis = yAxis2 + space
}
}
}
}
答案 0 :(得分:1)
你需要做的是先创建一个包含所有目标字母的数组(混洗并添加随机字母),然后在该数组上运行以更新按钮标题。
首先用随机字母填充14值数组:
var presentedLetters : [String] = [String]()
var availableLetters : [String] = pathDict?.object(forKey: "Letters") as! [String]
var availableLetterIndexes : [Int] = Array(0..<availableLetters.count)
for letterAt in 0 ..< 14
{
let randomIndex : Int = Int(arc4random_uniform(UInt32(availableLetterIndexes.count)))
var charIndex : Int = availableLetterIndexes[randomIndex]
presentedLetters.append(availableLetters[charIndex])
availableLetterIndexes.remove(at: randomIndex)
}
为答案字符串生成可用的位置:
var availableIndexes : [Int] = Array(0..<presentedLetters.count)
然后从数据库中删除你的信件并将它们添加到目标数组中的随机位置(同时记住添加的索引以防止覆盖字母):
var addedAnswerIndexes : [Int] = [Int]()
let answerString = data.ans // ans is a row in the SQLite database
let answerCharacters = answerString.characters.map{String($0)}
for answerCharAt in answerCharacters
{
let randomIndex : Int = Int(arc4random_uniform(UInt32(availableIndexes.count)))
var charIndex : Int = availableIndexes[randomIndex]
presentedLetters[charIndex] = answerCharAt
availableIndexes.remove(at: randomIndex)
}
然后presentLetters将包含所有相关值的数组。
修改强>
要将标题添加到按钮,只需查看presentLetters数组:
for i in 1...14 {
let tileButton = UIButton(type: .roundedRect)
tileButton.setTitle(presentedLetters[i-1], for: .normal)
......
}
}
祝你好运!