当我点击按钮时,我不想更改视图控制器只获取同一视图控制器上的按钮标题。我尝试了以下方式在scrollview中创建按钮。
class ViewController: UIViewController {
@IBOutlet weak var productScrollView: UIScrollView!
var buttonValues = ["Equity","Commodity","Derivatives","Market","Products","Values"]
override func viewDidLoad() {
super.viewDidLoad()
let scrollingView = colorButtonsView(buttonSize: CGSize(width:100.0,height:30.0), buttonCount: buttonValues.count)
productScrollView.contentSize = scrollingView.frame.size
productScrollView.addSubview(scrollingView)
productScrollView.showsHorizontalScrollIndicator = false
productScrollView.indicatorStyle = .default
productScrollView.setContentOffset(.zero, animated: false)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func colorButtonsView(buttonSize:CGSize, buttonCount:Int) -> UIView {
//creates color buttons in a UIView
let buttonView = UIView()
buttonView.backgroundColor = UIColor.white
buttonView.frame.origin = CGPoint(x:0,y:0)
let padding = CGSize(width:10,height:10)
buttonView.frame.size.width = (buttonSize.width + padding.width) * CGFloat(buttonCount)
buttonView.frame.size.height = (buttonSize.height + 2.0 * padding.height)
var buttonPosition = CGPoint(x:padding.width * 0.5,y: padding.height)
let buttonIncrement = buttonSize.width + padding.width
for i in 0...(buttonCount - 1) {
let button = UIButton(type: .custom) as UIButton
button.frame.size = buttonSize
button.frame.origin = buttonPosition
buttonPosition.x = buttonPosition.x + buttonIncrement
button.setTitle(buttonValues[i], for: .normal)
button.setTitleColor(UIColor.black, for: .normal)
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor
button.addTarget(self, action: #selector(colorButtonPressed(sender:)), for: .touchUpInside)
buttonView.addSubview(button)
}
return buttonView
}
@objc func colorButtonPressed(sender:UIButton!){
print(sender.title(for: .normal)!)
sender.setTitleColor(UIColor.blue, for: .normal)
}}