programing

Swift에서 프로그래밍 방식으로 UIButton 만들기

magicmemo 2023. 4. 21. 20:26
반응형

Swift에서 프로그래밍 방식으로 UIButton 만들기

저는 Swift로 UI를 프로그래밍 방식으로 구축하려고 합니다.

이 작업을 수행하려면 어떻게 해야 합니까?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let myFirstLabel = UILabel()
    let myFirstButton = UIButton()
    myFirstLabel.text = "I made a label on the screen #toogood4you"
    myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
    myFirstLabel.textColor = UIColor.redColor()
    myFirstLabel.textAlignment = .Center
    myFirstLabel.numberOfLines = 5
    myFirstLabel.frame = CGRectMake(15, 54, 300, 500)
    myFirstButton.setTitle("✸", forState: .Normal)
    myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
    myFirstButton.frame = CGRectMake(15, -50, 300, 500)
    myFirstButton.addTarget(self, action: "pressed", forControlEvents: .TouchUpInside)
    self.view.addSubview(myFirstLabel)
    self.view.addSubview(myFirstButton)
}

func pressed(sender: UIButton!) {
    var alertView = UIAlertView();
    alertView.addButtonWithTitle("Ok");
    alertView.title = "title";
    alertView.message = "message";
    alertView.show();
}

선택기 이름 끝에 대장이 빠져있네요를 누르면 파라미터가 적용되므로 콜론이 있어야 합니다.또한 누른 함수는 viewDidLoad 내부에 중첩되지 않아야 합니다.

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let myFirstLabel = UILabel()
    let myFirstButton = UIButton()
    myFirstLabel.text = "I made a label on the screen #toogood4you"
    myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
    myFirstLabel.textColor = .red
    myFirstLabel.textAlignment = .center
    myFirstLabel.numberOfLines = 5
    myFirstLabel.frame = CGRect(x: 15, y: 54, width: 300, height: 500)
    myFirstButton.setTitle("✸", for: .normal)
    myFirstButton.setTitleColor(.blue, for: .normal)
    myFirstButton.frame = CGRect(x: 15, y: -50, width: 300, height: 500)
    myFirstButton.addTarget(self, action: #selector(pressed), for: .touchUpInside)
}

@objc func pressed() {
    var alertView = UIAlertView()
    alertView.addButtonWithTitle("Ok")
    alertView.title = "title"
    alertView.message = "message"
    alertView.show()
}

편집: Swift 2.2의 베스트 프랙티스를 반영하도록 업데이트되었습니다.#selector()는 사용되지 않는 리터럴 문자열이 아니라 사용해야 합니다.

Swift 2.2 X 코드 7.3

버튼 콜백 방식에서는 Objective-C String Literals가 권장되지 않습니다.

let button:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
button.backgroundColor = UIColor.blackColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action:#selector(self.buttonClicked), forControlEvents: .TouchUpInside)
self.view.addSubview(button)

func buttonClicked() {
     print("Button Clicked")
}

Swift 3 X 코드 8

let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
button.backgroundColor = .black
button.setTitle("Button", for: .normal)
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

func buttonClicked() {
    print("Button Clicked")
}

Swift 4 X 코드 9

let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
button.backgroundColor = .black
button.setTitle("Button", for: .normal)
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

@objc func buttonClicked() {
    print("Button Clicked")
}

스위프트 4/5

let button = UIButton(frame: CGRect(x: 20, y: 20, width: 200, height: 60))
 button.setTitle("Email", for: .normal)
 button.backgroundColor = .white
 button.setTitleColor(UIColor.black, for: .normal)
 button.addTarget(self, action: #selector(self.buttonTapped), for: .touchUpInside)
 myView.addSubview(button)



@objc func buttonTapped(sender : UIButton) {
                //Write button action here
            }

스위프트 4

private func createButton {
    let sayButtonT = UIButton(type: .custom)
    sayButtonT.addTarget(self, action: #selector(sayAction(_:)), for: .touchUpInside)
}

@objc private func sayAction(_ sender: UIButton?) {

}

네, 시뮬레이터에서요셀렉터를 인식하지 못하는 경우가 있습니다. 버그가 있는 것 같습니다.당신의 코드가 아니더라도 액션명(셀렉터)을 변경했을 뿐입니다.그건 효과가 있다.

let buttonPuzzle:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
buttonPuzzle.backgroundColor = UIColor.greenColor()
buttonPuzzle.setTitle("Puzzle", forState: UIControlState.Normal)
buttonPuzzle.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
buttonPuzzle.tag = 22;
self.view.addSubview(buttonPuzzle)

선택기 함수의 예를 다음에 나타냅니다.

func buttonAction(sender:UIButton!) {
    var btnsendtag:UIButton = sender
    if btnsendtag.tag == 22 {            
        //println("Button tapped tag 22")
    }
}

이거 먹어봐..도움이 됐으면 좋겠는데...

override func viewDidLoad() {
super.viewDidLoad()  

    let btn = UIButton()
    btn.frame = CGRectMake(10, 10, 50, 50)  //set frame
    btn.setTitle("btn", forState: .Normal)  //set button title
    btn.setTitleColor(UIColor.redColor(), forState: .Normal) //set button title color
    btn.backgroundColor = UIColor.greenColor() //set button background color
    btn.tag = 1 // set button tag
    btn.addTarget(self, action: "btnclicked:", forControlEvents: .TouchUpInside) //add button action
    self.view.addSubview(btn) //add button in view

}

버튼 클릭 이벤트입니다.

func btnclicked(sender: UIButton!) 
{
    //write the task you want to perform on buttons click event..
}

UIuttontitleLabel 속성에 액세스하여 프로그래밍 방식으로 사용자 정의 UI 버튼을 만들 수 있습니다.

Swift의 Class Reference 단위:titleLabel 속성에 대해 "이 속성은 읽기 전용이지만, 자체 속성은 읽기/쓰기입니다.주로 버튼의 텍스트를 구성하는 데 이러한 속성을 사용합니다."

Swift에서는 titleLabel 속성을 다음과 같이 직접 변경할 수 있습니다.

let myFirstButton = UIButton()
myFirstButton.titleLabel!.text = "I made a label on the screen #toogood4you"
myFirstButton.titleLabel!.font = UIFont(name: "MarkerFelt-Thin", size: 45)
myFirstButton.titleLabel!.textColor = UIColor.red
myFirstButton.titleLabel!.textAlignment = .center
myFirstButton.titleLabel!.numberOfLines = 5
myFirstButton.titleLabel!.frame = CGRect(x: 15, y: 54, width: 300, height: 500)

편집

Swift 3.1 구문

Swift 5.0

        let button = self.makeButton(title: "Login", titleColor: .blue, font: UIFont.init(name: "Arial", size: 18.0), background: .white, cornerRadius: 3.0, borderWidth: 2, borderColor: .black)
        view.addSubview(button)
        // Adding Constraints
        button.heightAnchor.constraint(equalToConstant: 40).isActive = true
        button.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
        button.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -40).isActive = true
        button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -400).isActive = true
        button.addTarget(self, action: #selector(pressed(_ :)), for: .touchUpInside)

       // Define commmon method
        func makeButton(title: String? = nil,
                           titleColor: UIColor = .black,
                           font: UIFont? = nil,
                           background: UIColor = .clear,
                           cornerRadius: CGFloat = 0,
                           borderWidth: CGFloat = 0,
                           borderColor: UIColor = .clear) -> UIButton {
        let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle(title, for: .normal)
        button.backgroundColor = background
        button.setTitleColor(titleColor, for: .normal)
        button.titleLabel?.font = font
        button.layer.cornerRadius = 6.0
        button.layer.borderWidth = 2
        button.layer.borderColor = UIColor.red.cgColor
        return button
      }
        // Button Action
         @objc func pressed(_ sender: UIButton) {
                print("Pressed")
          }

여기에 이미지 설명 입력

Swift 3: Swift 3을 생성할 수 있습니다.UIButton프로그램적으로

예를 들어 메서드 범위 내에서ViewDidLoad()반드시 버튼에 구속조건을 추가해 주세요.그렇지 않으면 버튼이 표시되지 않습니다.

let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.target(forAction: #selector(buttonAction), withSender: self)
//button.backgroundColor etc

view.addSubview(button)

@objc func buttonAction() {
   //some Action
}

또는 글로벌 변수로서 범위를 벗어나면 어디에서나 액세스 할 수 있습니다.module

let button: UIButton = {
   let b = UIButton()
   b.translatesAutoresizingMaskIntoConstraints = false
   //b.backgroundColor etc
   return b
}()

그런 다음 제약 조건을 설정합니다.

func setupButtonView() {
   view.addSubview(button)
   button.widthAnchor.constraint(equalToConstant: 40).isActive = true
   button.heightAnchor.constraint(equalToConstant: 40).isActive = true
   // etc

}

나는 코딩에서 버튼을 만들고 구속조건을 설정하는 예를 들었다.이 코드에는 프로그래밍 방식으로 버튼 동작도 포함되어 있습니다.

import UIKit

class ViewController: UIViewController {
  
  
  lazy var button: UIButton! = {
    
    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.backgroundColor = .darkGray
    button.setTitleColor(.white, for: .normal)
    button.addTarget(self, action: #selector(didTaped(_:)), for: .touchUpInside)
    button.tag = 1
    button.setTitle("Tap", for: .normal)
    return button
    
  }()
  
  lazy var label: UILabel! = {
    
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textColor = .black
    label.font = .systemFont(ofSize: 17)
    label.textAlignment = .center
    return label
    
  }()
    
  override var preferredStatusBarStyle: UIStatusBarStyle{
    return .darkContent
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    self.view.backgroundColor = .white
    self.setConstraint()
    
  }
  
  @objc func didTaped(_ sender: UIButton){
    
    self.label.text = "No of times Taped: \(sender.tag)"
    self.button.tag += 1
    
  }
  
  func setConstraint(){
    
    self.view.addSubview(self.button)
    self.view.addSubview(self.label)
    
    NSLayoutConstraint.activate([
    
      self.button.heightAnchor.constraint(equalToConstant: 60),
      self.button.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width * 0.66),
      self.button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
      self.button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
      
      self.label.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
      self.label.topAnchor.constraint(equalTo: self.button.topAnchor, constant: UIScreen.main.bounds.height * 0.12),
      self.label.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 10),

    ])

  }
  
}

출력:

Swift: Ui 버튼은 프로그래밍 방식으로 생성,

var button: UIButton = UIButton(type: .Custom)

button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0)

button.addTarget(self, action: #selector(self.aMethod), forControlEvents: .TouchUpInside)

button.tag=2

button.setTitle("Hallo World", forState: .Normal)

view.addSubview(button)


func aMethod(sender: AnyObject) {
    print("you clicked on button \(sender.tag)")
}

UIButton을 위한(그리고 그 동안) 신속한 "버튼 팩토리" 확장도 다음과 같이 UILabel을 위한 것입니다.

extension UILabel
{
// A simple UILabel factory function
// returns instance of itself configured with the given parameters

// use example (in a UIView or any other class that inherits from UIView):

//   addSubview(   UILabel().make(     x: 0, y: 0, w: 100, h: 30,
//                                   txt: "Hello World!",
//                                 align: .center,
//                                   fnt: aUIFont,
//                              fntColor: UIColor.red)                 )
//

func make(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat,
          txt: String,
          align: NSTextAlignment,
          fnt: UIFont,
          fntColor: UIColor)-> UILabel
{
    frame = CGRect(x: x, y: y, width: w, height: h)
    adjustsFontSizeToFitWidth = true
    textAlignment = align
    text = txt
    textColor = fntColor
    font = fnt
    return self
}
// Of course, you can make more advanced factory functions etc.
// Also one could subclass UILabel, but this seems to be a     convenient case for an extension.
}


extension UIButton
{
// UIButton factory returns instance of UIButton
//usage example:

// addSubview(UIButton().make(x: btnx, y:100, w: btnw, h: btnh,
// title: "play", backColor: .red,
// target: self,
// touchDown: #selector(play), touchUp: #selector(stopPlay)))


func make(   x: CGFloat,y: CGFloat,
             w: CGFloat,h: CGFloat,
                  title: String, backColor: UIColor,
                  target: UIView,
                  touchDown:  Selector,
                  touchUp:    Selector ) -> UIButton
{
    frame = CGRect(x: x, y: y, width: w, height: h)
    backgroundColor = backColor
    setTitle(title, for: .normal)
    addTarget(target, action: touchDown, for: .touchDown)
    addTarget(target, action: touchUp  , for: .touchUpInside)
    addTarget(target, action: touchUp  , for: .touchUpOutside)

    return self
}
}

Xcode 버전 9.2 (9C40b) Swift 4.x에서 Swift로 테스트 완료

Swift: Ui 버튼이 프로그래밍 방식으로 생성됨

let myButton = UIButton() 
myButton.titleLabel!.frame = CGRectMake(15, 54, 300, 500) 
myButton.titleLabel!.text = "Button Label"
myButton.titleLabel!.textColor = UIColor.redColor()
myButton.titleLabel!.textAlignment = .Center

Swift 3 Xcode 8의 경우...

let button = UIButton(frame: CGRect(x: 0, y: 0, width: container.width, height: container.height))
        button.addTarget(self, action: #selector(self.barItemTapped), for: .touchUpInside)


func barItemTapped(sender : UIButton) {
    //Write button action here
}
   override func viewDidLoad() {
        super.viewDidLoad()
        let menuButton = UIButton(frame: .zero)
        menuButton.addTarget(self, action: #selector(menuTapped), for: .touchUpInside)
        view.addSubView(menuButton)
    }

    @objc func menuTapped() {
        // do Stuff
    }

제약이 있는 UIButtoniOS 9.1/Xcode 7.1.1/Swift 2.1:

import UIKit
import MapKit

class MapViewController: UIViewController {  

    override func loadView() {
        mapView = MKMapView()  //Create a view...
        view = mapView         //assign it to the ViewController's (inherited) view property.
                               //Equivalent to self.view = mapView

        myButton = UIButton(type: .RoundedRect)  //RoundedRect is an alias for System (tested by printing out their rawValue's)
        //myButton.frame = CGRect(x:50, y:500, width:70, height:50)  //Doesn't seem to be necessary when using constraints.
        myButton.setTitle("Current\nLocation", forState: .Normal)
        myButton.titleLabel?.lineBreakMode = .ByWordWrapping  //If newline in title, split title onto multiple lines
        myButton.titleLabel?.textAlignment = .Center
        myButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        myButton.layer.cornerRadius = 6   //For some reason, a button with type RoundedRect has square corners
        myButton.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.5) //Make the color partially transparent
        //Attempt to add padding around text. Shrunk the frame when I tried it.  Negative values had no effect.
        //myButton.titleEdgeInsets = UIEdgeInsetsMake(-10,-10,-10,-10)
        myButton.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5)  //Add padding around text.

        myButton.addTarget(self, action: "getCurrentLocation:", forControlEvents: .TouchUpInside)
        mapView.addSubview(myButton)

        //Button Constraints:
        myButton.translatesAutoresizingMaskIntoConstraints = false //***
        //bottomLayoutGuide(for tab bar) and topLayoutGuide(for status bar) are properties of the ViewController
        //To anchor above the tab bar on the bottom of the screen:
        let bottomButtonConstraint = myButton.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -20) //Implied call of self.bottomLayoutGuide. Anchor 20 points **above** the top of the tab bar.
        //To anchor to the blue guide line that is inset from the left 
        //edge of the screen in InterfaceBuilder:
        let margins = view.layoutMarginsGuide  //Now the guide is a property of the View.
        let leadingButtonConstraint = myButton.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor)

        bottomButtonConstraint.active = true
        leadingButtonConstraint.active = true
    }


    func getCurrentLocation(sender: UIButton) {
        print("Current Location button clicked!")
    }

버튼은 탭바 위 왼쪽 하단 모서리에 고정됩니다.

Swift We Can Make A 버튼은 뷰컨트롤러.swift 파일에 이 코드를 적어 프로그래밍 방식으로 만들 수 있습니다.

import UIKit

class ViewController: UIViewController
{  
private let firstbutton:UIButton = UIButton()

override func viewDidLoad() {
    super.viewDidLoad()
    self.firstbutton = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton
    self.firstbutton!.frame = CGRectMake(100, 200, 100, 100)
    self.firstbutton!.backgroundColor = UIColor.redColor()
    self.firstbutton!.setTitle("My Button", forState: UIControlState.Normal)
    self.firstbutton!.addTarget(self, action:#selector(self.firstButtonClicked), forControlEvents: .TouchUpInside)
    self.view.addSubview(firstbutton!)
    }

func firstButtonClicked(){
   print("First Button Clicked")
}

Swift 4.2 - XCode 10.1

폐쇄 사용

let button: UIButton = {
  let button = UIButton(type: .system)
  button.titleLabel?.font = UIFont.systemFont(ofSize: 20)
  ...
  return button
}()

iOS 12에서는 Swift 4.2 및 XCode 10.1

//For system type button
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 250, width: 100, height: 50)
//        button.backgroundColor = .blue
button.setTitle("Button", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13.0)
button.titleLabel?.textAlignment = .center//Text alighment center
button.titleLabel?.numberOfLines = 0//To display multiple lines in UIButton
button.titleLabel?.lineBreakMode = .byWordWrapping//By word wrapping
button.tag = 1//To assign tag value
button.btnProperties()//Call UIButton properties from extension function
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

//For custom type button (add image to your button)
let button2 = UIButton(type: .custom)
button2.frame = CGRect(x: 100, y: 400, width: 100, height: 50)
//        button2.backgroundColor = .blue
button2.setImage(UIImage.init(named: "img.png"), for: .normal)
button2.tag = 2
button2.btnProperties()//Call UIButton properties from extension function
button2.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button2)

@objc func buttonClicked(sender:UIButton) {
    print("Button \(sender.tag) clicked")
}

//You can add UIButton properties like this also
extension UIButton {
    func btnProperties() {
        layer.cornerRadius = 10//Set button corner radious
        clipsToBounds = true
        backgroundColor = .blue//Set background colour
        //titleLabel?.textAlignment = .center//add properties like this
    }
}

설정(iOS 15 서 apple apple 、 Apple 의 in in in in in in in in in in in in in in in in in in in in in in in in in in)이 되고 있습니다..gray(),.filled()기타)을 클릭합니다.을 사용하다

 var grayButton: UIButton!

 func addButton() {
    grayButton = UIButton(configuration: .gray())
    grayButton.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
    grayButton.frame = CGRect(x: 10, y: 50, width: 150, height: 50)
    grayButton.configuration?.title = "Press Me"
    grayButton.configuration?.subtitle = "Sub Title"
    grayButton.configuration?.image = UIImage(systemName: "house")
    grayButton.configuration?.imagePadding = 10
    grayButton.configuration?.imagePlacement = .leading
    view.addSubview(grayButton)
}

@objc func buttonPressed(_ sender: UIButton) {
    grayButton.configuration?.showsActivityIndicator = true
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
        self.grayButton.configuration?.showsActivityIndicator = false
    }
}

버튼 수 .showsActivityIndicator★★★★★★★★★★★★★★★★★★.

Swift UIkit에서 프로그래밍 방식으로 UIButton 작업 만들기

UIButton 작성

lazy var seeMoreBtn: UIButton = {
    let seeMoreBtn = UIButton()
    seeMoreBtn.translatesAutoresizingMaskIntoConstraints = false
    seeMoreBtn.setTitle("See More Answers", for: .normal)
    seeMoreBtn.setTitleColor(.systemBlue, for: .normal)

    //Action for  UIButton
    seeMoreBtn.addTarget(self, action: #selector(seeMorePressed), for: .touchUpInside)

    return seeMoreBtn
}()

@obj 함수 추가

@objc func seeMorePressed() {
 // Do something when click on Button
    print("see more answer button")
}

메인 스토리보드 부분과 오른쪽 하단에 있는 사각형 원으로 이동한 후 빈 버튼을 사용합니다.다음으로 코드 내에서 @IBAtion을 사용하여 배선합니다.그러면 @IBAtion 함수를 만들 수 있습니다.

언급URL : https://stackoverflow.com/questions/24102191/make-a-uibutton-programmatically-in-swift

반응형