gpt4 book ai didi

iOS:如何访问 UISegmentedControl 中的各个段?

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:09:23 25 4
gpt4 key购买 nike

这个问题相当简单,但我在许多 UISegmentedControl 帖子中没有看到任何真正满足我需求的内容:

环境:我有一组显示在 UISegmentedControl 中的目录。这是一个平面层次结构,目录很少,因此这是显示它们的最佳方式。

选择一个段会用该目录的内容填充下面的 UITableView。

我可以通过编程方式选择给定的片段,这样我就可以根据需要选择合适的片段。

效果很好。

问题:

其中一个目录是“默认”目录,它将包含现有项目和新项目的混合。

我想标记该片段,以便指示其中有多少新片段,以便人们知道选择它(如果尚未为他们选择的话)。

这意味着我需要访问 UISegmentedControl 中的实际 subview 和诸如此类的东西。

没那么简单。创建角标(Badge)是 children 的游戏。弄清楚角标(Badge)放在哪里是成年人的事。

看起来 Apple 有意隐藏对分割市场的直接访问。您只能影响整个控件。

关于我如何只修改一个片段,甚至找出该片段的位置,有没有人有任何建议?

widthForSegmentAtIndex: .功能似乎毫无值(value),因为它是否会给您任何有用的信息是任意的。

最佳答案

不,widthForSegmentAtIndex: 返回的值不是任意的。正如您在文档中看到的那样,它返回段的宽度或 0.0,这意味着段是自动调整大小的。

有一种方法可以获取每个片段的帧。

  1. 获取 UISegmentedControl 的宽度
  2. 询问每个段的宽度
    • 如果返回 0.0 则增加一个计数器
    • 否则从总宽度中删除段的宽度
  3. 将剩余宽度除以自动调整大小的段数,您就得到了每个自动调整段的大小。
  4. 您现在可以使用此信息来计算每个片段的帧。

或者在代码中:

据我在 iOS7 上看到的,段之间的“边界”不是段宽度的一部分。

CGFloat autosizedWidth = CGRectGetWidth(self.segment.bounds);
// iOS7 only?!
autosizedWidth -= (self.segment.numberOfSegments - 1); // ignore the 1pt. borders between segments


NSInteger numberOfAutosizedSegmentes = 0;
NSMutableArray *segmentWidths = [NSMutableArray arrayWithCapacity:self.segment.numberOfSegments];
for (NSInteger i = 0; i < self.segment.numberOfSegments; i++) {
CGFloat width = [self.segment widthForSegmentAtIndex:i];
if (width == 0.0f) {
// auto sized
numberOfAutosizedSegmentes++;
[segmentWidths addObject:[NSNull null]];
}
else {
// manually sized
autosizedWidth -= width;
[segmentWidths addObject:@(width)];
}
}

CGFloat autoWidth = floorf(autosizedWidth/(float)numberOfAutosizedSegmentes);
for (NSInteger i = 0; i < [segmentWidths count]; i++) {
id width = segmentWidths[i];
if (width == [NSNull null]) {
[segmentWidths replaceObjectAtIndex:i withObject:@(autoWidth)];
}
}

CGFloat x = CGRectGetMinX(self.segment.frame);
for (NSInteger i = 0; i < [segmentWidths count]; i++) {
NSNumber *width = segmentWidths[i];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, CGRectGetMaxY(self.segment.frame) + 1, [width floatValue], 30)];
view.backgroundColor = [UIColor colorWithHue:i/(float)[segmentWidths count] saturation:1 brightness:1 alpha:1];
[self.view addSubview:view];
x = CGRectGetMaxX(view.frame)+1;
}

这会产生以下结果:

enter image description here

我建议您不要将角标(Badge)添加为 UISegmentedControl 的 subview ,您可以将其添加到 segmentedControl 的 superView。您的角标(Badge)基本上应该是 segmentedControl 的兄弟


请提交 enhancement request与苹果公司。他们不会让我们访问各个 subview ,但他们至少可以告诉我们段的实际大小。

关于iOS:如何访问 UISegmentedControl 中的各个段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19126728/

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