【问题标题】:Math needed to correctly positioning subviews dynamically动态正确定位子视图所需的数学
【发布时间】:2012-05-21 23:56:21
【问题描述】:

漫长的一天,我的大脑似乎不想再与我合作了......

我为子视图数组中的每个视图迭代了一个 for 循环。每个子视图高度为 100 像素。当数组中有 1 项时,视图的 y 值需要设置为 0。当数组中有 2 项时,索引 0 处的视图需要 y 值为 100,索引处的项1 的 ay 值必须为 0。依此类推:

1 item: 0 = 0
2 items: 0 = 100, 1 = 0
3 items: 0 = 200, 1 = 100, 2 = 0
4 items: 0 = 300, 1 = 200, 2 = 100, 3 = 0

我需要能够仅根据数组中的项目数正确地动态处理此问题。这是我到目前为止的代码:

for (int i = 0; i < [subViews count]; i++) {
    NSView *v = (NSView *)[subViews objectAtIndex:i];
    [v setFrameOrigin:NSMakePoint(copy.view.frame.origin.x, i * 100)];//This gives me the opposite of what I want...
}

谢谢!

【问题讨论】:

    标签: iphone objective-c macos math logic


    【解决方案1】:
    int n = [subViews count];
    for (NSView *v in subViews) {
        n--;
        [v setFrameOrigin:NSMakePoint(copy.view.frame.origin.x, n * 100)];
    }
    

    【讨论】:

      【解决方案2】:

      在循环之前插入这个:
      int subviewCount = [subViews count];

      还有[subViews objectAtIndex: (subviewCount - i - 1)] 而不是[subViews objectAtIndex: i]

      【讨论】:

        【解决方案3】:

        这将起作用:

        y = 100 * ([subViews count] - 1 - i)
        

        另外,仅供参考,请尝试使用以下格式的 for 循环:

        for(NSView *thisView in subViews)
        {
            int i = [subViews indexOfObject:thisView]; //To get the "i position"
            //The rest of the code can be the same
        }
        

        这是因为如果 subViews 为空,for(int i = 0; i &lt; [subViews count]; i++) 循环将至少运行一次,并在执行 NSView *v = (NSView *)[subViews objectAtIndex:i]; 时崩溃

        如果 subViews 为空,for(NSView *thisView in subViews) 将不会执行。

        【讨论】:

        • 如果您必须在数组中搜索每个对象,则快速枚举不再很快。更好地跟踪索引(请参阅我的答案)。
        • 你是对的;虽然我建议这样做的原因是为了防止索引越界错误。获取 i 值的代码行是因为提问者在他的代码中使用了 i。
        猜你喜欢
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-02
        • 1970-01-01
        • 2017-11-03
        相关资源
        最近更新 更多