2012-01-31 3 views
2

Есть ли простой и простой способ изменить размер UIView после его создания и изменить его размеры?изменить размер подкласса uiview после создания

У меня есть пользовательские UIView подкласс под названием AnagramLetter, реализация и интерфейс код, который показан ниже:

@interface AnagramLetter : UIView{ 
    UILabel *letterLbl; 
    UIImageView *letterBG; 
} 
@property (nonatomic, retain) UILabel *letterLbl; 
@property (nonatomic, retain) UIImageView *letterBG; 
@end 


@implementation AnagramLetter 
@synthesize letterLbl,letterBG; 

- (id)initWithFrame:(CGRect)frame 
{ 
    frame = CGRectMake(0, 0, 166, 235); 
    CGRect lblFrame = CGRectMake(1, 1, 164,164); 
    self = [super initWithFrame:frame]; 
    [self setAutoresizesSubviews:YES]; 
    if (self) { 
     // Initialization code 
     letterBG = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"anagram_correct_bg.png"]]; 
     [self addSubview:letterBG]; 

     letterLbl = [[UILabel alloc] initWithFrame:lblFrame]; 
     letterLbl.backgroundColor = [UIColor clearColor]; 
     letterLbl.textColor = [UIColor blackColor]; 
     letterLbl.textAlignment = UITextAlignmentCenter; 
     letterLbl.numberOfLines = 0; 
     letterLbl.minimumFontSize = 50; 
     letterLbl.font = [UIFont boldSystemFontOfSize:144]; 
     letterLbl.adjustsFontSizeToFitWidth = YES; 
     [self addSubview:letterLbl]; 
    } 
    return self; 
} 
@end 

При нажатии кнопки на моем UI, я называю метод, который сгенерирует список из выше элементов и заполняет UIView вдоль своей оси X, создавая UIView для каждого символа в данной строке. Прежде чем я это сделаю, я получаю размеры UIView (называемые anagramHolder), деленные на количество символов в слове. Затем я устанавливаю рамки/фрейм UIView после его инициализации, но до сих пор не было изменений в поведении созданных представлений AnagramLetter.

Ниже приведен код, который я использую для получения измерений, изменение границ созданного подкласса и добавление элемента в файл anagramHolder UIView.

- (void) createAnagram { 
    float aWidth = 166.0; 
    float aHeight = 235.0; 
    CGRect rect = [anagramHolder bounds]; 

    if (!anagramCreated){ 
     for (int i=0; i<[word length]; i++) { 
      AnagramLetter *a; 
      if ((rect.size.width/[scrambled length]) < 166){ 
       float percentDiff = ((rect.size.width/[scrambled length])/166); 
       aWidth = (rect.size.width/[scrambled length]); 
       aHeight = aHeight * percentDiff; 
       CGRect newBounds = CGRectMake(0, 0, aWidth, aHeight); 
       a = [[AnagramLetter alloc] initWithFrame:newBounds]; 
      } 
      else { a = [[AnagramLetter alloc] init]; } 
      [a setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight]; 
      [a setAutoresizesSubviews:YES]; 

      CGPoint pos; 
      pos.x = (i * (rect.size.width/[scrambled length])) + (aWidth/2); 
      pos.y = (rect.size.height/2); 
      [a setCenter:pos]; 
      [a.letterLbl setText:[NSString stringWithFormat:@"%c",[scrambled characterAtIndex:i]]]; 
      a.tag = i; 
      [anagramHolder addSubview:a]; 
      [anagramLetters addObject:a]; 
      [a release]; 
     } 
    } 
    anagramCreated = YES; 
    [self getAnagramResult]; 
} 

ответ

3

Самый простой способ AUTORESIZE подвидов из view частности это установить соответствующее значение subviews свойства с именем autoresizingMask.

Например,

UIView *view; 
view.autoresizesSubviews = YES; 
UIView *subview; 
subview.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth; 
[view addSubview:subview]; 

От компании Apple Docs:

UIViewAutoresizing Specifies how a view is automatically resized. 

enum { 
    UIViewAutoresizingNone     = 0, 
    UIViewAutoresizingFlexibleLeftMargin = 1 << 0, 
    UIViewAutoresizingFlexibleWidth  = 1 << 1, 
    UIViewAutoresizingFlexibleRightMargin = 1 << 2, 
    UIViewAutoresizingFlexibleTopMargin = 1 << 3, 
    UIViewAutoresizingFlexibleHeight  = 1 << 4, 
    UIViewAutoresizingFlexibleBottomMargin = 1 << 5 }; 
typedef NSUInteger UIViewAutoresizing; 

Более подробную информацию можно найти здесь: UIView

P.S. Также я использую autoresizingMask для разработки своих приложений как для iPhone, так и для iPad.

+0

спасибо за ваш комментарий, я пробовал ваш выше код, как внутри моего файла AnagramLetter.m, так и в моем основном файле реализации, но все равно никакого эффекта. Любая идея, что я могу делать неправильно? –

+0

В моем файле реализации перед добавлением subview letterBG я добавил этот код: 'letterBG.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth; 'Аналогично, я добавил' letterLbl.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth; 'перед тем, как добавить letterLbl в качестве подкатегории –

+0

, просто попробуйте использовать другие комбинации маски. – Nekto

Смежные вопросы