[英]Add Button to UIView Created Programmatically
我以編程方式創建了UIView和Button
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完全相同的位置,寬度和高度
但結果是這樣
我的代碼有什么問題?
提前致謝
此問題是由以下代碼行引起的:
button.frame = newView.frame // Equivalent to button.frame = CGRectMake(4, 39, width, height)
在當前的實現中,button的x位置為4,y位置為39,這就是為什么要以這種方式獲得結果的原因。 您需要指定相對於newView的按鈕框架。
將按鈕框設置代碼更改為:
button.frame = CGRectMake(0, 0, width, height)
您應該使用bounds
而不是視圖的框架。
button.frame = newView.bounds
Bounds在其自己的坐標空間中返回視圖坐標的CGRect,而frame在其父坐標空間中返回相同的CGRect。
因此newView.bounds將返回一個CGRect,例如(0,0,width_of_newView,height_of_newview)
您的按鈕框是錯誤的。
當您聲明框架的x和y屬性時,它與其父視圖相關。
由於您將按鈕框聲明為(4,39,寬度,高度),因此它將被放置在與您的圖片完全相同的視圖框中,坐標x = 4,y = 39。
如果要使其像您的視圖一樣,請將x和y更改為0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.