2014-05-07 63 views
0

我想實現三個視圖的自定義佈局。該視圖用於「酒吧」,「俱樂部」和「食物」類別。實施與故事板的自定義視圖佈局

這些類別中的每一個都會擁有自己的自定義圓視圖。內圓視圖將是具有文本標籤。

當前設置
目前三個視圖被添加到故事板,並給予相關的UIView子類。子類然後處理使它們成爲圓圈並添加標籤。

- (id)init { 
    self = [super init]; 
    if (self) { 
     [self setupView]; 
    } 
    return self; } 

-(void)setupView { 
    self.translatesAutoresizingMaskIntoConstraints = NO; 
    float newRadius = self.frame.size.width/2; 
    self.layer.cornerRadius = newRadius; // TODO/TEST - The UIImageView is set to 40x40 and the frame is yet to be created 
    self.layer.masksToBounds= YES; 

    self.layer.borderWidth = 5; 
    self.layer.borderColor = [UIColor colorWithRed:0.138 green:0.225 blue:1.000 alpha:1.000].CGColor; 


    self.backgroundColor = [self randomColor]; 

    [self setupLabel]; 
} 

-(void)setupLabel { 
    UILabel *label = [[UILabel alloc]init]; 
    label.translatesAutoresizingMaskIntoConstraints = NO; 
    label.text = @"Test"; 
    label.textColor = [UIColor whiteColor]; 
    label.text = [label.text uppercaseString]; 
    [self addSubview:label]; 

    [self addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]]; 
    [self addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]]; 
} 

然而,與上面的設置我無法想象我將如何實現與不同的標籤文本每圈有何看法?

什麼是處理這種自定義視圖和佈局的最佳方式。代碼中完全創建圓視圖並更改自定義init方法以傳遞標籤的NSString更好嗎?

回答

1

您可以在自定義UIView中創建一個名爲text的屬性,然後使用User Runtime Attributes來更改它。

在界面生成器,你可以有:

enter image description here

然後你就可以在你的CustomView覆蓋:

// This method will get called for each attribute you define. 
-(void) setValue:(id)value forKey:(NSString *)key { 
    if ([key isEqualToString:@"text"]) { 
     self.mylabel.text = value; 
    } 
} 

請注意,您需要在您的標籤中的一個屬性。 @property (nonatomic, weak) UILabel* myLabel所以,當你設置你的標籤,你將需要:

-(void)setupLabel { 
    UILabel *label = [[UILabel alloc]init]; 
    //... 
    [self addSubview:label]; 

    //the label, since it is weak, needs to be added to the visual tree first 
    self.myLabel = label; 
} 
+0

這不工作我,這是正確的?當註銷標籤框架時,我得到0,0,並且在註銷框架文本時,我得到空值,但是我一直按照這個步驟進行。 – StuartM

+0

self.text在哪裏設置? – StuartM

+0

是的,self.text實際上並不需要,請更新'self.mylabel.text = value;' – StuartM