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

프로그래밍 방식으로 UI를 작성하려고합니다. 이 작업을 어떻게 수행합니까? Swift로 개발 중입니다.

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 = 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 = 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: #selector(myClass.pressed(_:)), forControlEvents: .TouchUpInside)
    self.view.addSubview(myFirstLabel)
    self.view.addSubview(myFirstButton)
}

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

편집 : Swift 2.2의 모범 사례를 반영하여 업데이트되었습니다. 더 이상 사용되지 않는 리터럴 문자열 대신 #selector ()를 사용해야합니다.


답변

스위프트 2.2 Xcode 7.3

버튼 콜백 메소드에서 Objective-C 문자열 리터럴이 더 이상 사용되지 않으므로

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")
}

스위프트 3 Xcode 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")
}

스위프트 4 Xcode 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")
    }
}


답변

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

클래스 참조 스위프트의 다음에 관한 titleLabel의 속성을, 그것은 “이 속성은 읽기 전용 있지만, 자신의 속성이 읽기 / 쓰기 버튼의 텍스트를 구성하는 기본적으로 이러한 속성을 사용합니다..”고 말했다

에서 스위프트 , 당신은 직접적 같은 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)

편집하다

스위프트 3.1 구문


답변

이것들을 사용해보십시오. 도움이되기를 바랍니다 …

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..
}