![](/img/trans.png)
[英]How can a UIView subclass get notified when it has been scrolled by its Superview UIScrollView
[英]How can a UIView get a callback when it is added to its superview?
我已经将UIView子类化了。 将此子类的对象添加到其superview后,它需要自动运行一些代码。 如何挂钩此事件以运行我的代码?
UISegmentedControl的所选分段的背景众所周知难以设计。 我能找到的最好的解决方案是做这个黑客:
#import "SegmentedControlStyled.h"
@implementation SegmentedControlStyled
- (void) updateStyle
{
for (NSUInteger i = 0; i < [self.subviews count]; i++) {
if ([[self.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && [[self.subviews objectAtIndex:i] isSelected]) {
[[self.subviews objectAtIndex:i] setTintColor:[UIColor colorWithWhite:0.7 alpha:1.0]];
}
if ([[self.subviews objectAtIndex:i] respondsToSelector:@selector(isSelected)] && ![[self.subviews objectAtIndex:i] isSelected]) {
[[self.subviews objectAtIndex:i] setTintColor:[UIColor colorWithWhite:0.9 alpha:1.0]];
}
}
}
@end
需要在两个地方调用此updateStyle
函数。 显然,第一个是用户点击不同的段时。 我可以通过覆盖我的SegmentedControlStyled
的addTarget
函数并挂钩到UIControlEventValueChanged
事件来自动执行此操作。 在将SegmentedControlStyled
添加到其superview 之后 ,需要调用第二个地方updateStyle
。 您可能会问,“为什么要在之后调用它而不是像init
那样的地方?”。 好吧,从我的观察来看,在它被附加到视图之前调用它是没有效果的。 因此,需要像这样编写代码:
SegmentedControlStyled* seg = [[SegmentedControlStyled alloc] initWithItems:[NSArray arrayWithObjects:@"One", @"Two", nil]];
[self.view addSubview:seg];
[seg updateStyle];
最后一行是丑陋的,因为使用我的子类的同事必须理解为什么视图被破坏并且必须知道何时调用updateStyle
。 为了坚持面向对象的封装原则,这个细节应该移到类本身。 如果我能够检测何时将视图添加到其superview中,我将能够将样式hack封装在我的子类中。
覆盖任何一个
- (void)didAddSubview:(UIView *)subview
- (void)willMoveToSuperview:(UIView *)newSuperview
- (void)willMoveToWindow:(UIWindow *)newWindow
作为适当的?
UISegmentedControl的选定状态并不难。
您使用方法setBackgroundImage:forState:barMetrics:
并使用UIControlStateSelected
作为命名参数forState:
参数forState:
。
您访问UIKit控件子视图的任何内容都是件坏事。 您不应该依赖内部实现细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.