chucklai
chucklai

Reputation: 844

how to customize a button's size in swift 3?

I want to resize a button as a square and here's my code:

    let button = UIButton()
    button.backgroundColor = UIColor.red

    button.translatesAutoresizingMaskIntoConstraints = false

    //method one 
    //button.widthAnchor.constraint(equalToConstant:44.0).isActive = true
    //button.heightAnchor.constraint(equalToConstant: 44.0).isActive = true
    //method two
    button.frame.size = CGSize(width: 20.0, height: 20.0)

    button.addTarget(self, action: #selector(ratingButtonTapped(button: )), for: .touchUpInside)
    addArrangedSubview(button)

I have tried both method however none of them seem to work out fine with an error showing some mistakes in method one and nothing shown in method two. when i run the code, button is fulfilled in the container. what is wrong here?

Upvotes: 4

Views: 16830

Answers (2)

Christian Ascone
Christian Ascone

Reputation: 1177

Use addSubview() instead of addArrangedSubview().

I write here the playground with the same solution I posted in comments, in case someone encounters the same problem:

Swift 3.0:

//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 400))

view.backgroundColor = UIColor.blue

let button = UIButton()
button.backgroundColor = UIColor.red
button.frame.size = CGSize(width: 40.0, height: 20.0)
button.translatesAutoresizingMaskIntoConstraints = false

view.addSubview(button) // This does the trick

PlaygroundPage.current.liveView = view

Upvotes: 6

Saheb Roy
Saheb Roy

Reputation: 5967

Why not create the button and initialise it with the given size?

let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))

And then change the x and y accordingly

Upvotes: -2

Related Questions