• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

c# - F#:从 ViewController 中的 Storyboard访问 UI 元素?

[复制链接]
菜鸟教程小白 发表于 2022-12-13 02:24:27 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

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

MyButton.TouchUpInside += (object sender, EventArgs e) =>
{
...
}

我正在尝试在 F# 中执行相同的操作,但它无法识别 Controller 中的“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/



Best Answer-推荐答案


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

let mutable _fsharpButton = null :> UIButton

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

完整的 ViewController 示例:

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

我个人只是通过代码创建 UI 并跳过 Storyboard 设计器...

关于c# - F#:从 ViewController 中的 Storyboard访问 UI 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45360541/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap