ios - UIView 类在循环结束时被调用

标签 ios swift core-data uiview

我是 swift 编程新手,正在测试一些场景。

我有一个 UIView 类,我用它来绘制一些东西。我将使用 for 循环多次将此 UIView 类作为 subview 添加到我的主视图 Controller 中。

我在 coredata 中有一个实体,它存储我使用 UIVIew 类所做的绘图的配置信息。每个条目都会包含 ID、尺寸等详细信息以及绘图所需的一些其他详细信息。

从 coredata 获取数据后,我使用“for”循环迭代每个条目,然后使用从 coredata 检索的数据进行绘制(UIView 类作为 subview )。

循环的每次迭代都需要使用 UIView 类创建新的 subview ,其中包含从 coredata 检索的尺寸和其他详细信息。但我注意到它循环遍历所有条目并在循环末尾调用 UIView 类,即使 .addsubView 位于循环中间。

我可以看到它创建了与核心数据条目相同数量的 subview ,但由于 View 是在循环结束时调用的,因此所有 subview 都是使用最后一个条目核心数据的详细信息创建的。

我的代码是这样的。请帮我解决这个问题。谢谢。

主视图 Controller 。

   let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext
    do {
        let request = NSFetchRequest(entityName: "Projects")
        let results = try context.executeFetchRequest(request)
        if results.count > 0 {
            GlobalVariable.sharedManager.starty = 50
            for item in results as! [NSManagedObject]{
        let titleout = String(item.valueForKey("title")!)
                    let startxp1 = item.valueForKey("startx")
                    let startxp2 = item.valueForKey("starty")
        let projtag = item.valueForKey("pid")

        GlobalVariable.sharedManager.title = titleout 
                let DrawLanes = DrawProj(frame: CGRect(x: startx, y: starty, width: 500, height: 200))
                DrawLanes.backgroundColor = UIColor.clearColor()
                DrawLanes.userInteractionEnabled = true
        DrawLanes.tag = projtag 
                MainScroller.addSubview(DrawLanes)

            }
        }
    }catch {
        print ("there was an error in fetch")
    }

绘图

override func drawRect(rect: CGRect) {

    let button = UIButton(type: .System) // let preferred over var here
    button.frame = CGRectMake(24, 15, 300, 20)
    button.backgroundColor = UIColor.orangeColor()
    button.userInteractionEnabled = false
button.text = GlobalVariable.sharedManager.title
    self.addSubview(button)

}

最佳答案

我认为失败点是GlobalVariable.sharedManager.title = titleout并且实例化 View 并不意味着它的drawRect将被调用。

我的解决方案是在 DrawLanes 中创建一个新变量,并使用 titleout 初始化变量

DrawLines.buttonTitle = titleout

并在drawRect中放置

button.title = self.buttonTitle

关于ios - UIView 类在循环结束时被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39182046/

相关文章:

ios - 即使执行了更改图像的代码,按钮的图像也没有改变

ios - 如何计算UITableView中标题的正确高度

iphone - 使用 NSSortDescriptor

swift - 找不到接受提供的参数的 '__conversion' 的重载,将多个元素添加到数组

swift - 无法在 Ubuntu 中安装 Swift

ios - 核心数据多对多关系插入数据错误

ios - 我可以在 ViewDidLoad 中加载 UICollectionView 的数据吗?

ios - 如何调整 Core Data 默认缓存的行为或大小?

iphone - 在 iphone 应用程序中从 UIScrollView 创建 PDF

ios - 如何以编程方式从 UIViewController 转到 UITableViewController