[英]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.