2014-02-24 64 views
0

我想創建具有圖像和編號的UIView。我想集中他們。現在我有這樣的代碼:iOS - UIView的中心內容

CGRect likesRect = CGRectMake(0,152, screenWidth/2, 30); 
    MARoundedRect *likesRoundedRect = [[MARoundedRect alloc] initWithFrame:likesRect]; 

    UIView *likesView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 30)]; 
    likesView.center = CGPointMake(screenWidth/4, 20); 

    UIImageView *likeImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)]; 
    likeImage.image = [UIImage imageNamed:@"favorite.png"]; 

    UILabel *likesLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 0, screenWidth/2, 20)]; 
    [likesLabel setTextColor:[UIColor whiteColor]]; 
    [likesLabel setBackgroundColor: [UIColor clearColor]]; 
    [likesLabel setText:[actualPlace.Favorites stringValue]]; 

    [likesView addSubview:likeImage]; 
    [likesView addSubview:likesLabel]; 
    [likesRoundedRect addSubview:likesView]; 
    [viewController.view addSubview:likesRoundedRect]; 

現在它的工作不錯,但我設置likesView的寬度精確值,我想這變壞的時候,我沒有數與一個或兩個字母,但更多。我怎樣才能解決這個問題?如果兩個或多個組件並排存在,如何集中UIView的內容?或者我如何設置UIView動態改變寬度的內容?由於

+0

您能使用自動佈局? – Wain

+0

我想是的,它只能在代碼中(以編程方式)。 –

回答

0

我不寫完整代碼,但你嘗試用下面的代碼,

CGRect likesRect = CGRectMake(0,152, screenWidth/2, 30); 
MARoundedRect *likesRoundedRect = [[MARoundedRect alloc] initWithFrame:likesRect]; 

CGSize likeViewSize = CGSizeMake(50,30); 
UIView *likesView = [[UIView alloc] init]; 
likesView.frame = CGRectMake(likesRoundedRect.frame.size.width/2 - likeViewSize.width/2,likesRoundedRect.frame.size.height/2 - likeViewSize.height/2,likeViewSize.width,likeViewSize.height); 

我都集中在其parentview的likesView。你必須做同樣的事情標籤和ImageView的,如果你要居中他們在他們的parentview(likesView

0

的UIView和它的子類有一個屬性叫做中心:

CGPoint center1 = CGPointmake(self.view.bounds.size.width/2, 
     self.view.bounds.size,height/2) ; 

    subview.center = center1; 

下面的討論是從Apple關於UIView的文檔:

@property(非原子)CGPoint中心 討論 中心在其超級視圖的座標系中指定,並以點爲單位進行度量。設置此屬性會相應地更改框架屬性的值。

更改框架矩形會自動重新顯示接收器而不調用drawRect:方法。如果要在框架矩形更改時調用drawRect:方法,請將contentMode屬性設置爲UIViewContentModeRedraw。

此屬性的更改可以爲動畫。使用beginAnimations:context:類方法開始,使用commitAnimations類方法結束動畫塊。

供貨情況 適用於iOS 2.0及更高版本。 請參見 @property框架 @property界 @property變換 關聯的例子代碼 AVLoupe 處理倒是採用響應的方法和姿勢識別 iAdInterstitialSuite iAdSuite RosyWriter 宣佈 UIView.h