UIView
उप-वर्गीकरण करते समय, मैं आमतौर पर अपने सभी प्रारंभिकरण और लेआउट कोड को init
विधि में रखता हूं। लेकिन मुझे बताया गया है कि layoutSuviews
ओवरराइड करके लेआउट कोड किया जाना चाहिए। SO पर post है जो बताता है जब प्रत्येक विधि को कॉल किया जाता है, लेकिन मैं जानना चाहता हूं कि अभ्यास में उनका उपयोग कैसे करें।UIView: layoutSubviews बनाम initWithFrame
मैं वर्तमान में इस तरह init
विधि में अपने सभी कोड डाल दिया,:
MyLongView.m
- (id)initWithHorizontalPlates:(int)theNumberOfPlates
{
self = [super initWithFrame:CGRectMake(0, 0, 768, 1024)];
if (self) {
// Initialization code
_numberOfPlates = theNumberOfPlates;
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.frame];
[scrollView setContentSize:CGSizeMake(self.bounds.size.width* _numberOfPlates, self.bounds.size.height)];
[self addSubview:scrollView];
for(int i = 0; i < _numberOfPlates; i++){
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"a1greatnorth_normal_%d.jpg", i+1]];
UIImageView *plateImage = [[UIImageView alloc] initWithImage:img];
[scrollView addSubview:plateImage];
plateImage.center = CGPointMake((plateImage.bounds.size.width/2) + plateImage.bounds.size.width*i, plateImage.bounds.size.height/2);
}
}
return self;
}
यह हमेशा की तरह कार्य है:, दृश्य की फ्रेम सेट करते समय एक इवर initialising, की स्थापना एक स्क्रॉलव्यू अप करें, यूआईएममेज शुरू करना, उन्हें UIImageViews में रखना, उन्हें बाहर रखना।
मेरा प्रश्न है: इनमें से कौन सा init
में किया जाना चाहिए, और इनमें से कौन सा layoutSubviews
में किया जाना चाहिए?
मैं इसे और नीचे दबा दूंगा। Init के बजाय 'viewDidLoad' में अपनी सबव्यू ऑब्जेक्ट बनाएं। विचार आलसी लोड हो जाते हैं, और अगर पर्यवेक्षण नहीं किया जा रहा है तो सबव्यूव्यू बनाने का कोई कारण नहीं है। – Abizern
हम यहां विचारों के बारे में बात कर रहे हैं, न कि ViewController। – calimarkus