gpt4 book ai didi

arrays - 通过数据库中的字符使用 for 循环创建 UILabel

转载 作者:行者123 更新时间:2023-11-28 06:16:04 26 4
gpt4 key购买 nike

我正在通过 SQLite 数据库中的字符使用 For 循环创建 UILabe,我该怎么做?

这是我的代码:

for data in listdata {
for tar in [data.ans.characters] as NSArray {
var counter = ""
counter = tar as! String
let targetLabel = UILabel(frame: CGRect(x: xAxis, y: yAxis, width: 50, height: 50))
targetLabel.backgroundColor = .white
targetLabel.layer.masksToBounds = true
targetLabel.layer.cornerRadius = 5
targetLabel.text = counter
targetLabel.textAlignment = .center
self.view.addSubview(targetLabel)
}
}

data.ans 是字符串数据,我将其转换为字符数组,它是从 listdata 派生的,当我输入前面的代码时,我崩溃了!他的按摩是:

Could not cast value of type 'Swift.String.CharacterView'

当编辑我的代码时:

for data in listdata {
for tar in AnyObject[data.ans.characters] as NSArray { // Instance member 'subscript' cannot be used on type 'AnyObject'
var counter = ""
counter = tar as String
let targetLabel = UILabel(frame: CGRect(x: xAxis, y: yAxis, width: 50, height: 50))
targetLabel.backgroundColor = .white
targetLabel.layer.masksToBounds = true
targetLabel.layer.cornerRadius = 5
targetLabel.text = counter
targetLabel.textAlignment = .center
self.view.addSubview(targetLabel)
}
}

给我错误消息:

Instance member 'subscript' cannot be used on type 'AnyObject'

解决了什么?我如何根据 SQLite 数据库中的字符数循环 UILabel?

我想在图片中像这样创建,但是来自 SQLite 数据库 (data.ans):

enter image description here

最佳答案

characters 属性已经是可迭代的。您还有另外两个问题:

  1. 您需要将 tar 转换为 String 以将其分配给 .text 属性
  2. 您需要为每次迭代添加 width 以及 x 的一些增量

代码

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 345, height: 70))

class Data {
var ans = "LONDON"
}
var data = Data()
var x = 10
var y = 10
for tar in data.ans.characters {
let targetLabel = UILabel(frame: CGRect(x: x, y: y, width: 50, height: 50))
x += 50 + 5
targetLabel.backgroundColor = .white
targetLabel.layer.masksToBounds = true
targetLabel.layer.cornerRadius = 5
targetLabel.text = String(tar)
targetLabel.textAlignment = .center
view.addSubview(targetLabel)
let xString = String(format: "%\(03)d", x)
print("x = \(xString), tar = \(tar)")
}

PlaygroundPage.current.liveView = view
PlaygroundPage.current.needsIndefiniteExecution = true

这是在 Swift playground 中运行的。

LONDON

从菜单中选择 View -> Assistant Editor -> Show Assistant Editor 以查看 UIView

输出

x =  65, tar = L
x = 120, tar = O
x = 175, tar = N
x = 230, tar = D
x = 285, tar = O
x = 340, tar = N

关于arrays - 通过数据库中的字符使用 for 循环创建 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45104394/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com