gpt4 book ai didi

iphone - 当 UIView 添加到它的父 View 时,它如何获得回调?

转载 作者:可可西里 更新时间:2023-11-01 03:41:58 25 4
gpt4 key购买 nike

问题

我已经子类化了一个 UIView .这个子类的一个对象被添加到它的父 View 之后,它需要自主运行一些代码。我怎样才能连接到这个事件来运行我的代码?

为什么我需要它

所选分段的背景UISegmentedControl众所周知,很难设计风格。我能找到的最佳解决方案是执行此 hack:

#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 函数需要在两个地方调用。显然,第一个是每当用户点击不同的部分时。我可以通过覆盖 SegmentedControlStyledaddTarget 函数并连接到 UIControlEventValueChanged 事件来自主执行此操作。 updateStyle 需要调用的第二个地方是 SegmentedControlStyled 添加到其父 View 之后。您可能会问,“为什么在之后而不是像 init 这样的地方调用它?”。好吧,根据我的观察,在它附加到 View 层次结构之前调用它没有任何效果。因此,需要这样写他们的代码:

SegmentedControlStyled* seg = [[SegmentedControlStyled alloc] initWithItems:[NSArray arrayWithObjects:@"One", @"Two", nil]];
[self.view addSubview:seg];
[seg updateStyle];

最后一行很难看,因为使用我的子类的同事必须了解为什么 View 被破坏并且必须知道何时调用 updateStyle。秉持面向对象的原则encapsulation ,这个细节应该移到类本身。如果我有能力检测何时将 View 添加到其父 View ,我就可以将样式 hack 封装在我的子类中。

最佳答案

覆盖其中一个

- (void)didAddSubview:(UIView *)subview
- (void)willMoveToSuperview:(UIView *)newSuperview
- (void)willMoveToWindow:(UIWindow *)newWindow

是否合适?

关于iphone - 当 UIView 添加到它的父 View 时,它如何获得回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17795825/

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