2015-12-02 44 views
-1

我創建的UIView和按鈕編程Add按鈕的UIView創建編程

var width = self.view.frame.width - 8 
     var height = width/8 

     newView.frame = CGRectMake(4, 39, width, height) 
     newView.backgroundColor = UIColor.greenColor() 
     self.view.addSubview(newView) 

     var button = UIButton.buttonWithType(UIButtonType.System) as! UIButton 
     button.frame = newView.frame 
     button.backgroundColor = UIColor.whiteColor() 
     button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside) 
     button.setTitle(" All Hospitals/Clinics", forState: UIControlState.Normal) 
     button.setTitleColor(UIColor.blackColor(), forState: .Normal) 
     button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left 
     newView.addSubview(button) 

我希望按鈕是UIView的內部,並具有完全相同的位置,寬度和UIView的

的高度

但結果是這樣的

enter image description here

什麼是錯我的代碼?

在此先感謝

+0

? –

+0

@ SohilR.Memon是的我正在使用autolayout,但我需要這個按鈕被編程創建 – Maha

+0

然後,你必須在編程創建UI時也給出約束! –

回答

4

這個問題是由下面這行代碼引起的:

button.frame = newView.frame // Equivalent to button.frame = CGRectMake(4, 39, width, height) 

在你當前實現按鈕的x座標爲4和y位置是39,這就是爲什麼你得到結果就像那樣。您需要指定相對於newView的按鈕框架。

更改按鈕框設置代碼:

button.frame = CGRectMake(0, 0, width, height) 
1

你的按鈕幀是錯誤的。

當您聲明幀的x和y屬性時,它與其超級視圖有關。由於您將您的按鈕框架聲明爲(4,39,寬度,高度),因此它將放置在座標x = 4,y = 39的視圖框架中,與您的圖片完全相同。

,如果你想讓它像你的觀點,改變x和y爲0

3

您應該使用bounds,而不是觀點的框架。

button.frame = newView.bounds 

邊界返回視圖的座標的CGRect在其自己的座標空間,而幀返回相同的,但在它的父級座標空間。

所以newView.bounds將您是否使用自動佈局返回一個的CGRect喜歡(0,0,width_of_newView,height_of_newview)