要创建一个UIButton以显示与UIBarButtonItem相同的效果,您需要遵循以下步骤:
let customButton = UIButton(type: .system)
customButton.setTitle("Button Title", for: .normal)
customButton.titleLabel?.font = UIFont.systemFont(ofSize: 17)
customButton.backgroundColor = UIColor.clear
customButton.layer.borderWidth = 1
customButton.layer.borderColor = UIColor.lightGray.cgColor
customButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16)
customButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
@objc func buttonTapped() {
print("Custom UIButton tapped")
}
view.addSubview(customButton)
customButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
customButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),
customButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16)
])
现在,您已经创建了一个UIButton,它具有与UIBarButtonItem相同的效果。您可以根据需要自定义其外观和行为。
领取专属 10元无门槛券
手把手带您无忧上云