首页 > 解决方案 > 如何使可点击的 NSAttributedString 移动到另一个 ViewController Swift

问题描述

我正在开发一个简单的应用程序并以编程方式添加NSAttributedString. 我真的很困惑如何将礼物viewcontroller转移到另一个viewcontroller

这不是重复的问题,因为我的问题是关于如何移动到查看控制器和重复问题如何在点击时打开链接 如何在 NSAttributedString 中创建可点击的链接?.

截屏

截屏

在上图中显示三个NSAttributedString第一个是dhiman.sham1gmail.com,第二个是has started following和第三个Sham。尝试单击时Sham不执行任何操作。单击时,我想将此控制器移动到另一个控制器Sham

这是我的代码:

@IBOutlet weak var descriptionLbl: UILabel!

override func updateWithModel(_ model: AnyObject) {
 self.descriptionLbl.attributedText = self.followingGetTextFromType(data: (model as? FollowingNotificationData)!)
}

func followingGetTextFromType(data:FollowingNotificationData) -> NSMutableAttributedString{
  var attributedString = NSMutableAttributedString()
  attributedString = NSMutableAttributedString(string:(data.detailsNoti?.fullName)!, attributes: strres)
  let startedfollowing = NSMutableAttributedString(string:" has started following ", attributes: attrs)
  attributedString.append(startedfollowing)
  var discription = NSMutableAttributedString()
  if data.fullName == ""{
  discription = NSMutableAttributedString(string:"\((data.userName)!)", attributes: strres)
  }else{
  discription = NSMutableAttributedString(string:"\((data.fullName)!)", attributes: strres)
  }
  attributedString.append(discription)
}

有人可以向我解释如何解决这个问题,我已经尝试解决这个问题但还没有结果。

任何帮助将不胜感激。

提前致谢。

标签: iosswiftuiviewcontrollernsattributedstringnsattributedstringkey

解决方案


尝试使用此代码制作NSMutableAttributedString,您可以根据需要将其动态化,以将动态字符串值作为参数传递。

安装UItextView_UIlabel

@IBOutlet weak var descriptionLbl: UITextView!

descriptionLbl.attributedText = prepareAttributedTextString()

func prepareAttributedTextString() -> NSMutableAttributedString {

        let masterString = "dhiman@gmail.com has started following Sham"

        let formattedString = NSMutableAttributedString(string: masterString)

        let ShamUseAttribute = [
            NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue,
            NSAttributedStringKey.font: UIFont.systemFont(ofSize: 16.0),
            NSAttributedStringKey.link: URL(string: "Sham")!,
            ] as [NSAttributedStringKey : Any]


        let ShamRange = (masterString as NSString).range(of: "Sham")
        formattedString.addAttributes(ShamUseAttribute, range: ShamRange)

        return formattedString
    }

使用它UITextViewDelegate来检测点击UItextView并预测到指定UIviewController

// MARK: UITextView Delegate Method
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

       if (URL.absoluteString == "Sham") { 
             let objVC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "YourViewController") as! YourViewController           
             self.navigationController?.pushViewController(objVC, animated: true)
        }
        return true
    }

从情节提要中设置以下属性。

在此处输入图像描述


推荐阅读