关于 c#:F#:从 ViewController 中的故事板访问 UI 元素?

F#: Accessing UI Elements from storyboard in ViewController?

这里是 F# 新手,并尝试在纯 F# 中构建 Xamarin.iOS 应用程序。在 C# 中,当我在 Storyboard 编辑器中放置一个 UI 元素并为其命名,并且在 Storyboard 中引用控制器时,我能够访问该控制器中的 UI 元素。
即我在故事板中创建了一个名为 MyButton 的按钮。现在在控制器中我想添加一个动作,假设创建一个警报,在 C# 中我可能会写

1
2
3
4
MyButton.TouchUpInside += (object sender, EventArgs e) =>
{
...
}

我正在尝试在 F# 中执行相同的操作,但它无法识别控制器中的 "MyButton"。有什么帮助吗?

更新:我做了一些研究,像往常一样,大部分来源都有几年的历史。 C# 能够从设计器引用对象的方式是通过项目模板生成关联的 YourController.designer.cs 文件,这些文件从设计器引用对象。这是一个部分类。根据这篇有趣的博客文章:

http://7sharpnine.com/2013/02/03/2013-02-03-monotouch-and-fsharp-part-i/

,此功能在 F# 中不可用,因为"F# 中缺少部分类使得 UI 设计人员难以将工具紧密集成到 F#",他声称他将致力于此那篇博文是 4.5 年前的,所以我希望有人解决了这个问题......请建议

更新 2:同一个博客在 4 年后再次出现并再次解决了这个问题
http://7sharpnine.com/2017/04/11/i-want-to-tell-you-a-storyboard/


假设您在 ViewController 上定义了一个名为 "fsharpButton" 的 UIButton,您定义了一个 Outlet 来获取 VC 对象引用并在运行时将其分配给可变对象,然后您可以连接触摸事件。

1
2
3
4
5
6
let mutable _fsharpButton = null :> UIButton

[<Outlet>]
member this.fsharpButton
       with get() = _fsharpButton
       and set value = _fsharpButton <- value

完整的视图控制器示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
namespace ios_fsharp_foo

open System
open Foundation
open UIKit

[<Register ("ViewController")>]
type ViewController (handle:IntPtr) =
    inherit UIViewController (handle)

    let mutable _fsharpButton = null :> UIButton

    let addUpdateHandler =
        new EventHandler (fun sender eventargs ->
            Console.WriteLine("Hello StackOverflow")
    )

    [<Outlet>]
    member this.fsharpButton
           with get() = _fsharpButton
           and set value = _fsharpButton <- value

    override x.DidReceiveMemoryWarning () =
        // Releases the view if it doesn't have a superview.
        base.DidReceiveMemoryWarning ()
        // Release any cached data, images, etc that aren't in use.

    override x.ViewDidLoad () =
        base.ViewDidLoad ()
        // Perform any additional setup after loading the view, typically from a nib.
        _fsharpButton.TouchUpInside.AddHandler addUpdateHandler

    override x.ShouldAutorotateToInterfaceOrientation (toInterfaceOrientation) =
        // Return true for supported orientations
        if UIDevice.CurrentDevice.UserInterfaceIdiom = UIUserInterfaceIdiom.Phone then
           toInterfaceOrientation <> UIInterfaceOrientation.PortraitUpsideDown
        else
           true

我个人只是通过代码创建用户界面并跳过故事板设计器...


一些邪恶的天才通过类型提供程序解决了问题。很不错的东西!为那些不得不在 2017 年 4 月之前编码的悲伤灵魂感到抱歉!哇哈哈!

http://7sharpnine.com/2017/04/11/i-want-to-tell-you-a-storyboard/