gpt4 book ai didi

swift - 如何在一个按钮上添加另一个按钮?

转载 作者:行者123 更新时间:2023-11-30 10:25:39 24 4
gpt4 key购买 nike

一切正常,但是当我尝试从 configureAddButton() 调用 createSecondContainer () 方法时,它不起作用。也就是说,按下按钮本身不起作用。

override func viewDidLoad() {
super.viewDidLoad()

configureMainContainer()
}

func configureMainContainer(){
view.addSubview(mainContainer)

let frame = CGRect(x: view.bounds.midX - 60, y: view.bounds.midY, width: 120, height: 40)

mainContainer.frame = frame
mainContainer.addTarget(self, action: #selector(showAlert), for: .touchUpInside)
configureAddButton()
}

func configureAddButton(){
mainContainer.addSubview(addButton)
let frame = CGRect(x: mainContainer.bounds.maxX + 5, y: mainContainer.bounds.midY / 2, width: 20, height: 20)
addButton.frame = frame

addButton.addTarget(self, action: #selector(createSecondContainer), for: .touchUpInside)
}

@objc func createSecondContainer(){
print("something to complete")
}

最佳答案

您可以正常使用此代码

import UIKit

class ViewController: UIViewController {

let mainContainer = UIButton()

override func viewDidLoad() {
super.viewDidLoad()


}

override func viewDidAppear(_ animated: Bool) {
configureMainContainer()

}

func configureMainContainer(){

let frame = CGRect(x: view.bounds.midX - 60, y: view.bounds.midY, width: 120, height: 40)
mainContainer.frame = frame
mainContainer.addTarget(self, action: #selector(showAlert), for: .touchUpInside)
mainContainer.backgroundColor = UIColor.red
self.view.addSubview(mainContainer)

configureAddButton()
}

@objc func showAlert() {
// Your Alert Code here

}

func configureAddButton(){

let addButton = UIButton()
let frame = CGRect(x: mainContainer.bounds.midX, y: mainContainer.bounds.midY / 2, width: 20, height: 20)
addButton.frame = frame
addButton.addTarget(self, action: #selector(createSecondContainer), for: .touchUpInside)
addButton.backgroundColor = UIColor.blue
mainContainer.addSubview(addButton)
}

@objc func createSecondContainer(){
print("something to complete")
}


}

关于swift - 如何在一个按钮上添加另一个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60068097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com