gpt4 book ai didi

ios - Swift:如何在 ScrollView 中使用按钮

转载 作者:搜寻专家 更新时间:2023-11-01 07:27:15 25 4
gpt4 key购买 nike

我创建了一个带有“按钮”的 ScrollView 。但是“按钮”目前实际上没有做任何事情。所以,我想知道如何使“按钮”可用。因此,当我按下它们时,它们会将我带到另一个 View Controller 。所有按钮都会将我带到同一个 View Controller ,只是在 View Controller 内具有不同的数据(取决于我希望该按钮代表什么)。到目前为止,这是我的代码:

     @IBOutlet weak var categoryScrollView: UIScrollView!
var categoryArr = ["Button1","Button2","Button3","Button4","Button5", "Button 6", "Button 7", "Button 8", "Button 9", "Button 10", "Button 11", "Button 12"]
var buttonColors = [UIColor.greenColor(), UIColor.blueColor(), UIColor.blackColor(), UIColor.cyanColor(), UIColor.magentaColor(), UIColor.greenColor(), UIColor.blueColor(), UIColor.blackColor(), UIColor.cyanColor(), UIColor.magentaColor(), UIColor.blackColor(), UIColor.brownColor()]
let kPadding:CGFloat = 20

override func viewDidLoad() {
super.viewDidLoad()

let buttonSize = CGSizeMake(categoryScrollView.bounds.size.width/2, categoryScrollView.bounds.size.height/2)//hal

let scrollingView = colorButtonsView(buttonSize, buttonCount: 12)
categoryScrollView.contentSize = scrollingView.frame.size
categoryScrollView.addSubview(scrollingView)
categoryScrollView.showsVerticalScrollIndicator = false
categoryScrollView.delegate = self
categoryScrollView.pagingEnabled = true
categoryScrollView.indicatorStyle = .Default
categoryScrollView.contentOffset = CGPointMake(0, 0)
}


func colorButtonsView(buttonSize:CGSize, buttonCount:Int) -> UIView {
let buttonView = UIView()
buttonView.frame.origin = CGPointMake(50,300)
let padding = CGSizeMake(kPadding, kPadding)
buttonView.frame.size.width = (buttonSize.width + padding.width) * CGFloat(buttonCount)
var buttonPosition = CGPointMake(0, padding.height)
let buttonIncrement = buttonSize.width + padding.width
for i in 0...(buttonCount - 1) {
let button = UIButton(type: .Custom)
button.frame.size = buttonSize
button.frame.origin = buttonPosition
buttonPosition.x = buttonPosition.x + buttonIncrement
button.setTitle(categoryArr[i], forState: UIControlState.Normal)
button.backgroundColor = buttonColors[i]
buttonView.addSubview(button)
}
buttonView.backgroundColor = UIColor.redColor()
return buttonView
}
}
extension ViewController:UIScrollViewDelegate{
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {

let index = round(scrollView.contentOffset.x / scrollView.frame.size.width)
print(index)
}

最佳答案

当您创建按钮时,您必须指定一个目标以便对其执行操作(将其添加到您的 for 循环中):

 button.addTarget(self, action: "myaction:", forControlEvents: .TouchUpInside)

然后创建对应的方法

 func myaction(sender: UIButton!) {
// navigation code here.
}

请注意,您不必创建多个方法来为每个按钮执行不同的操作,您所要做的就是像这样:

 button.tag = i

然后在您的操作方法中:

switch sender.tag {

case 0 :
//do some stuff

case 1 :
//do some stuff

}

关于ios - Swift:如何在 ScrollView 中使用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35193359/

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