Maha
Maha

Reputation: 529

Add Button to UIView Created Programmatically

I created UIView and Button programmatically

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)

I want the button to be inside the UIView, and to have exactly the same location, width and height of UIView

but the result is this

enter image description here

What is wrong with my code ?

Thanks in advance

Upvotes: 1

Views: 7228

Answers (4)

Hailey
Hailey

Reputation: 362

you can use Anchor

lazy var testButton: UIButton = {

  let button = UIButton()

  button.translatesAutoresizingMaskIntoConstraints = false
  button.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
  button.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
  button.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
  button.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

  return button

}()

override func viewDidLoad() {
  self.view.addSubview(testButton)
}

Upvotes: 0

mohonish
mohonish

Reputation: 1396

You should use bounds instead of the frame of the view.

button.frame = newView.bounds

Bounds returns the CGRect of the view coordinates in its own coordinate space, while frame returns the same but in it's parent's coordinate space.

So newView.bounds would return a CGRect like (0,0,width_of_newView,height_of_newview)

Upvotes: 5

seto nugroho
seto nugroho

Reputation: 1379

your button frame is wrong.

when you declared x and y property of a frame, it is related to its superview.

since you declare your button frame as (4, 39, width, height) it will be placed on coordinate x = 4, y = 39 in view's frame which is exactly like your picture.

if you want to make it like your view, change x and y to 0.

Upvotes: 1

Midhun MP
Midhun MP

Reputation: 107121

The issue is caused by this line of code:

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

In your current implementation the x position of button is 4 and y position is 39, that's why you are getting the result like that way. You need to specify the button frame relative to the newView.

Change the button frame setting code to:

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

Upvotes: 7

Related Questions