2014-02-15 52 views
2

我想设置我的应用程序,以便我可以将NSUrl属性添加到textview的指定子字符串,并且当触摸NSUrl时,它会推送新视图而不是打开新的url 。自定义URL处理iOS xamarin

我ovverriding的OpenURL我AppDelegate.cs类,在我的类,它包含的文本视图的URL发送通知

public override bool OpenUrl (UIApplication application, NSUrl url, string sourceApplication, NSObject annotation) 
{ 
     NSNotificationCenter.DefaultCenter.PostNotification (NSNotification.FromName ("ArtistDetail", url)); 

     return true; 
} 

然后,我添加了观察员在构造

NSNotificationCenter.DefaultCenter.AddObserver ("ArtistDetail", delegate{artistDetail(null);}); 

而且有我的方法

public void artistDetail (NSNotification notification) 
    { 
     //push view based on info in notification.object 
    } 

我没有任何运气。我发现这篇文章Can't push view controller after overriding openURL有人以同样的方式在目标C中做到这一点。一个问题 - 我在OpenURL覆盖中放置断点和日志记录,并且它们没有被击中。当你点击/点击NSSUrl时,默认情况下是否调用OpenUrl?如果是这样,为什么不是我的重写命中?

+0

可能的重复http://stackoverflow.com/questions/21323338/ios7-uitextview-set-nslinkattributename-attribute-but-can-not-click – JiaYow

+0

@JiaYow我的问题不是如何将URL添加到textview 。我的问题是如何在触摸时动态处理URL –

+0

我链接的问题有一个答案,可以解释为什么你的OpenUrl没有被调用。 – JiaYow

回答

3

我一直在研究如何做6个小时。当然,在我把问题发布到SO后的20分钟后,我找出答案。

我不得不实现一个UIApplication子类,重写那里的方法,注册它,然后启动它作为我Main.c中的UIApplication。

UIApplicationMain.cs

[Register ("UIApplicationMain")] 
public class UIApplicationMain : UIApplication 
{ 
    public UIApplicationMain() 
    { 
    } 

    public override bool OpenUrl (NSUrl url) 
    { 
     NSNotificationCenter.DefaultCenter.PostNotification (NSNotification.FromName ("ArtistDetail", url)); 

     return true; 

    } 
} 

Main.cs

public class Application 
{ 
    // This is the main entry point of the application. 
    static void Main (string[] args) 
    { 
     // if you want to use a different Application Delegate class from "AppDelegate" 
     // you can specify it here. 
     UIApplication.Main (args, "UIApplicationMain", "AppDelegate"); 
    } 

} 

- 视图 - 控制器,其中显示的超链接,并应处理动态推视图控制器你想

public override void ViewDidLoad() 
{ 
     base.ViewDidLoad(); 

     NSNotificationCenter.DefaultCenter.AddObserver ("ArtistDetail", artistDetail); 
} 
public void artistDetail (NSNotification notification) 
{ 
     NSUrl artistName = (NSUrl)notification.Object; 

     String name = artistName.AbsoluteString; 
     this.NavigationController.PushViewController (new ArtistDetailViewController (name), true); 
} 

对于任何试图解决“如何在您的UITextView中放置按钮”问题的人 (就像twitter与#hastags和@users一样) - 就是这样!将文本放入一个NSAttributedString中,将链接属性应用于要用作按钮的文本,然后进行相应处理。