Swift:Cell或Label是UIcollectionView中的http链接

时间:2016-03-18 21:16:55

标签: xcode swift uicollectionview

我正在开发一款利用UICollectionView显示内容的应用。我想让单元格或标签成为将在safari中打开的链接(http)。

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate  {

var tableData: [String] = ["Data1", "Data2", "Data3"]
var tableImages: [String] = ["img1.png", "img2.jpg", "img3.jpg"]






override func viewDidLoad() {




    // Do any additional setup after loading the view, typically from a nib.
}


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return tableData.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: colvwCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! colvwCell

    cell.lblCell.text = tableData[indexPath.row]
    cell.imgCell.image = UIImage(named: tableImages [indexPath.row])
    return cell

}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    print("Cell \(indexPath.row) selected")

}

2 个答案:

答案 0 :(得分:0)

最好的方法是使用带有属性字符串的UITextView:

swift 2.1

var str = "Google"
var attributedString = NSMutableAttributedString(string:str, attributes:[NSLinkAttributeName: NSURL(string: "http://www.google.com")!])

yourTextView.attributedText = attributedString

你可以为UILabel尝试这个库:https://github.com/AliSoftware/OHAttributedStringAdditions/wiki/link-in-UILabel

答案 1 :(得分:0)

我建议使用UITextView来显示和处理点击链接。 代码应该是以下

@IBOutlet private weak var textView: UITextView!

override func viewDidLoad() {
     super.viewDidLoad()
     textView.linkTextAttributes = [NSForegroundColorAttributeName: UIColor.blueColor()]

     let text = NSMutableAttributedString()
     text.beginEditing()
     text.appendAttributedString(NSAttributedString(string: "google", attributes: [NSLinkAttributeName: NSURL(string: "http://www.google.com")!]))
     text.endEditing()

     textView.attributedText = text
}

还需要在IB中设置UITextView委托并实现此功能

func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
        return true
}

并且不要忘记在IB中启用链接检测 enter image description here