我有以下代码尝试使用带有字母的scrollView。在viewDidLoad中,我创建并添加图像到scrollView和数组 - imgs [UIImageView]。当我检查imgs数组中某个项目的索引时,它会在第一个打印上返回一个可选值(在viewDidLoad方法中),但是我添加了tapGestureRecognizer,希望能够在点击后找到数组中的图像,但是当我在tapGesture处理程序中打印imgs.getIndexOf时,我得到nil(数组计数是正确的)。关于如何解决的任何想法?
class ViewController: UIViewController {
@IBOutlet weak var myScrollView: UIScrollView!
private let lettersModel:LettersModel = LettersModel();
private var imgs = [UIImageView]();
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(myScrollView)
var yPosition:CGFloat = 0
var scrollViewContentSize:CGFloat=0;
let imageWidth:CGFloat = myScrollView.frame.width
let imageHeight:CGFloat = myScrollView.frame.width
let spacer:CGFloat = 20
for var index=0; index<lettersModel.letters.count; index++
{
let myImage:UIImage = UIImage(named: lettersModel.getLetterAt(index))!
let myImageView:UIImageView = UIImageView()
myImageView.image = myImage
myImageView.contentMode = UIViewContentMode.ScaleAspectFit
myImageView.frame.size.width = imageWidth
myImageView.frame.size.height = imageHeight
myImageView.frame.origin.y = yPosition
myScrollView.addSubview(myImageView)
yPosition+=imageHeight + spacer
scrollViewContentSize+=imageHeight + spacer
myScrollView.contentSize = CGSize(width: imageWidth, height: scrollViewContentSize)
imgs.append(myImageView)
print("viewDidLoad indexOf = \(imgs.indexOf(myImageView))")
let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:Selector("imageTapped:"))
myImageView.userInteractionEnabled = true
myImageView.addGestureRecognizer(tapGestureRecognizer)
}
}
func imageTapped(img: UIImageView)
{
print("imageTapped indexOf = \(imgs.indexOf(img))")
}
}
LOG:
viewDidLoad indexOf = Optional(0)
viewDidLoad indexOf = Optional(1)
viewDidLoad indexOf = Optional(2)
viewDidLoad indexOf = Optional(3)
viewDidLoad indexOf = Optional(4)
viewDidLoad indexOf = Optional(5)
viewDidLoad indexOf = Optional(6)
viewDidLoad indexOf = Optional(7)
viewDidLoad indexOf = Optional(8)
viewDidLoad indexOf = Optional(9)
viewDidLoad indexOf = Optional(10)
viewDidLoad indexOf = Optional(11)
viewDidLoad indexOf = Optional(12)
viewDidLoad indexOf = Optional(13)
viewDidLoad indexOf = Optional(14)
点击手势记录:
imageTapped indexOf = nil
答案 0 :(得分:1)
您的imageTapped
函数签名错误; action
的{{1}}应该有一个参数:手势识别器本身。这应该有效:
UIGestureRecognizer