Как найти UIView, когда нет self.view?

Итак, я некоторое время боролся с этим как новичок с iOS - я уверен, что это либо основная концепция, которую я упускаю, либо свойство, с которым я еще не сталкивался, на которое мне нужно ссылаться.

Сценарий: Контроллер представления создает UIScrollView. UIView создается как контейнер для нескольких UILabels (описывающих событие, место и время). Метод вызывается повторно для создания этих UILabels внутри блока. Создание этих меток по одной работает нормально - просто добавляя каждую в представление, но когда я перемещаю код в метод и повторно использую его, абстрагируя такие вещи, как размер текста, отступ и т. д., я не могу ссылаться на одно и то же родительское представление. (потому что это не контроллер представления?) или выполните поиск с помощью viewWithTag (ничего не возвращает), чтобы найти родителя.

Это простое решение, или моя базовая структура ошибочна? Заранее большое спасибо за ваше время!

Заголовок:

//
//  ScheduleColumn.h
//

#import <Foundation/Foundation.h>

@interface ScheduleColumn : UIView {

}

- (void)makeTextBlock:(int)parentViewID label:(NSString*)label textSize:(int)textSize indent:(int)indent y:(int)y width:(int)width height:(int)height;

@end

Выполнение:

//
//  ScheduleColumn.m
//

#import "ScheduleColumn.h"

@implementation ScheduleColumn

// makeTextBlock: type, text, textSize, indent, build_y, width, height

// type: 0 = Title, 1 = Subtitle, 2 = Times
// text: Line content
// textSize: self-explanatory
// indent: indent from left side of parent
// build_y: # of units down from top of parent view to build
// width & height: self-explanatory

- (void)makeTextBlock:(int)parentViewID label:(NSString*)label textSize:(int)textSize indent:(int)indent y:(int)y width:(int)width height:(int)height {

    double unixTime;

unixTime = [[NSDate date] timeIntervalSince1970];

NSLog(@"makeTextBlock called");
NSLog(@"parentViewID: %u", parentViewID);
NSLog(@"label: %@", label);
NSLog(@"textSize: %u", textSize);
NSLog(@"indent: %u", indent);
NSLog(@"y: %u", y);
NSLog(@"width: %u", width);
NSLog(@"height: %u", height);
NSLog(@"time: %u", unixTime);

UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(indent, y, width, height)];   
textView.backgroundColor = [UIColor clearColor];
textView.textColor = [UIColor whiteColor];
textView.lineBreakMode = UILineBreakModeWordWrap;
textView.numberOfLines = 0;
textView.tag = unixTime;

textView.font = [UIFont fontWithName:@"PetitaMedium" size: textSize];
textView.text = label;

CGSize constraintTextSize;
constraintTextSize.width = width;
constraintTextSize.height = MAXFLOAT;
CGSize theTextSize = [label sizeWithFont:[UIFont fontWithName:@"PetitaMedium" size: textSize] constrainedToSize:constraintTextSize lineBreakMode:UILineBreakModeWordWrap];

CGRect newTextFrame = textView.frame;
newTextFrame.size.height = theTextSize.height;
textView.frame = newTextFrame;

UIView *parentView = (UIView *)[self.view viewWithTag:parentViewID];

[parentView addSubview:textView];
[textView release];

NSLog(@"--- break ---");

}

.. и, наконец, вызовы из View Controller:

int build_y;
int subtitle_indent;

build_y = 30;
subtitle_indent = 20;

UIView *blockView = [[UIView alloc] initWithFrame: CGRectMake ( 0, build_y, 185, 50)];
blockView.tag = 100;
[FireworksContent addSubview:blockView];

// Add top line
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, blockView.bounds.size.width, 0.5)];
lineView.backgroundColor = [UIColor whiteColor];
[blockView addSubview:lineView];

// Add Block Text
ScheduleColumn *blockText = [ScheduleColumn alloc];
[blockText makeTextBlock:blockView.tag label:@"Venue" textSize:18 indent:subtitle_indent y:build_y width:blockView.bounds.size.width height:20];
[blockText makeTextBlock:blockView.tag label:@"ShowTitle" textSize:12 indent:subtitle_indent y:build_y width:blockView.bounds.size.width height:20];
[blockText makeTextBlock:blockView.tag label:@"Showtime" textSize:36 indent:subtitle_indent y:build_y width:blockView.bounds.size.width height:20];


[lineView release];
[blockText release];

[blockView release];

... строка viewWithTag терпит неудачу, потому что у «я» нет представления ... изменение класса на UIViewController позволяет ему работать, но все равно без радости.


person JSpread    schedule 20.04.2011    source источник


Ответы (1)


Метод класса, возвращающий новое представление, а не метод экземпляра, возвращающий void, имел бы больше смысла.

+(UIView *)makeTextBlock:(int)parentViewID label:(NSString*)label textSize:(int)textSize indent:(int)indent y:(int)y width:(int)width height:(int)height

Создайте представление по своему усмотрению и верните это представление в конце метода.

Затем вы можете создать несколько таких представлений и сохранить ссылку на них в своем контроллере представления, если хотите.

UIView *blockText1 = [ScheduleColumn makeTextBlock .....];
[self.view addSubview: blockText1];
person Michael Behan    schedule 20.04.2011
comment
....аааа вот почему я люблю Интернет. Вы, сэр, джентльмен. Мне нужно мыслить предметами, а не сценариями! Кстати, после addSubview нужно двоеточие. :) Большое спасибо за ваше время! - person JSpread; 20.04.2011