AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-1151334

soleil's questions

Martin Hope
soleil
Asked: 2025-02-08 02:04:02 +0800 CST

SwiftUI 中的双粘性标题

  • 5

以下是尝试双粘性标题视图的完整代码示例:

struct ContentView: View {
    var body: some View {
        ScrollView(showsIndicators: false) {
            LazyVStack(spacing: 0, pinnedViews: .sectionHeaders) {
                Section {
                    SecondView()
                } header: {
                    HeaderView()
                }
            }
        }
    }
}

struct HeaderView: View {
    var body: some View {
        Rectangle()
            .fill(.green)
            .frame(height: 50)
    }
}

struct SecondView: View {
    var body: some View {
        LazyVStack(spacing: 0, pinnedViews: .sectionHeaders) {
            Section {
                VStack {
                    ForEach(0..<20) { index in
                        ItemView(index: index)
                    }
                }
            } header: {
                SecondHeaderView()
            }
        }
    }
}

struct SecondHeaderView: View {
    var body: some View {
        Rectangle()
            .fill(.red)
            .frame(height: 60)
    }
}

struct ItemView: View {
    let index: Int
    var body: some View {
        VStack {
            Text("Item \(index)")
                .padding()
        }
        .frame(height: 80)
        .background(.gray)
    }
}

#Preview {
    ContentView()
}

请注意,最初,红色的SecondHeaderView正确位置位于绿色的下方HeaderView。但是,滚动时,红色标题会滚动到绿色标题下方,直到它停留在与绿色标题相同的 y 位置。

我需要红色标题固定在绿色标题下方。请注意,SecondView可能并不总是嵌入在中ContentView。它可以独立存在,但仍然需要自己的单个粘性标题才能工作,因此我认为两个视图都需要LazyVStack。

我弄乱了各种 GeometryReader 视图偏移,试图让红色标题正确定位,但我无法做到正确。

swiftui
  • 1 个回答
  • 37 Views
Martin Hope
soleil
Asked: 2025-01-03 04:49:35 +0800 CST

SwiftUI scrollview 粘性标题而不使用列表

  • 5

我一直在努力解决这个问题GeometryReader,.onChange(of: geo.frame(in: .global).minY)但一直没有取得很大成功。考虑以下几点:

struct TestScreen: View {
    
    var body: some View {
        NavigationStack {
            ScrollView {
                VStack {
                    Text("View A")
                        .frame(height: 50)
                        .frame(maxWidth: .infinity)
                        .background(.green)
                    Text("View B - Sticky")
                        .frame(height: 50)
                        .frame(maxWidth: .infinity)
                        .background(.blue)
                    ForEach(0..<15) { i in
                        Text("View \(i)")
                            .frame(height: 50)
                            .frame(maxWidth: .infinity)
                            .background(Color.red)
                    }
                }
                
            }
            .navigationBarTitleDisplayMode(.inline)
            .toolbarBackground(.clear, for: .navigationBar)
            .toolbar {
                ToolbarItem(placement: .principal) {
                    Text("Testing")
                        .foregroundColor(.purple)
                }
            }
        }
    }
}

目标是让视图 B 在向上滚动视图时固定在顶部(导航栏下方),当然,在向下滚动时,它会占据滚动视图中的正常位置。我知道您可以使用和来实现粘性标题,List但这Sections不符合我的需要,因为请注意,视图 B(粘性视图)不一定是滚动视图中的第一个项目。

还要注意,视图 B 必须位于 VStack 中所有其他内容的顶部,以便其他内容在其下方滚动。

swiftui
  • 1 个回答
  • 28 Views
Martin Hope
soleil
Asked: 2024-12-29 14:10:14 +0800 CST

Unity中的预制乐谱文本动画

  • 5

我创建了一个名为 ScorePopup 的简单预制件。它有一个TextMeshPro组件。它还有一个Animator将文本向上移动 2 个世界单位并在 1 秒内淡出颜色的组件。因此在动画器中,它有

ScorePopup: Text Mesh Pro.Font Color - goes from 1 to 0 over 1 second.
ScorePopup: Anchored Position
  Anchored Position.x (stays at 0)
  Anchored Position.y - goes from 0 to 2 over 1 second.

现在,想象一下这样一个游戏,敌人从右向左移动。它被子弹击中。我想在敌人被击中的位置实例化这个 ScorePopup。

我尝试在我的游戏脚本中实例化它:

GameObject go = Instantiate(scorePopupPrefab, enemy.transform.position, Quaternion.identity);
go.GetComponent<TMP_Text>().text = score.ToString();

问题是 ScorePopup 没有出现在敌人的位置 - 它出现在我的场景中的 0,0,大概是因为Anchored Position动画中的值。

因此我尝试在敌人脚本中实例化 ScorePopup:

GameObject go = Instantiate(scorePopupPrefab, transform.position, Quaternion.identity, transform);

这样可以正确地将分数弹出窗口置于敌人所在的位置。但是,分数弹出窗口会随敌人向左移动。我希望分数弹出窗口出现在场景/世界空间中的打击位置并在那里执行动画。它不应该随敌人移动。

这里的解决方案是什么?如果预制件具有内部位置动画,如何在场景中的指定位置实例化预制件?这是针对非常常见的情况,当玩家通过击打或获得物体获得积分时,您会看到分数向上浮动。

编辑:文本预制件没有画布。它被创建为一个空对象,并TMPRo - Text添加了一个组件(和一个动画器)来显示文本。

我也尝试过这个:

public class ScorePopup : MonoBehaviour
{
    private Animator animator;

    void Awake()
    {
        animator = GetComponent<Animator>();
        if (animator != null)
        {
            animator.enabled = false;
            StartCoroutine(EnableAnimatorAfterDelay(0.1f));
        }
    }

    IEnumerator EnableAnimatorAfterDelay(float delay)
    {
        yield return new WaitForSeconds(delay);
        animator.enabled = true;
    }
}

它会短暂地出现在正确的位置,但当动画启用时它会移动到 0,0 :(

unity-game-engine
  • 2 个回答
  • 32 Views
Martin Hope
soleil
Asked: 2024-11-10 00:14:47 +0800 CST

为什么我的游戏对象在其变换发生改变时却不动?

  • 6

我试图平稳地将物体从 a 点移动到 b 点:

    Instantiate(cat, OffScreenLeft(), Quaternion.identity);
    Debug.Log("start position: " + OffScreenLeft());
    Debug.Log("end position: " + InPosition());

    StartCoroutine(MoveFromTo(cat.transform, OffScreenLeft(), InPosition(), 3f));
    
    IEnumerator MoveFromTo(Transform objectToMove, Vector3 a, Vector3 b, float speed) {
            float step = (speed / (a - b).magnitude) * Time.fixedDeltaTime;
            float t = 0;
            while (t <= 1.0f) {
                t += step; // Goes from 0 to 1, incrementing by step each time
                objectToMove.position = Vector3.Lerp(a, b, t); // Move objectToMove closer to b
                yield return new WaitForFixedUpdate();
            }
            objectToMove.position = b;
            Debug.Log("move complete cat: " + cat.transform.position); 
        }

这是调试输出:

    start position: (-20.34, 4.33)
    end position: (-8.67, 4.33)
    move complete cat: (-8.67, 4.33, 0.00)

调试输出显示猫应该移动了。但它仍然出现在屏幕外,留在原来的位置。我遗漏了什么?

unity-game-engine
  • 1 个回答
  • 34 Views
Martin Hope
soleil
Asked: 2024-11-03 03:19:51 +0800 CST

让物体随时间旋转回零

  • 6

在协同程序中我设置了刚体的速度来跟随触摸屏的位置:

rb.velocity = direction * touchDragPhysicsSpeed;

但我还想让它的旋转趋向于零度。我该怎么做?

人工智能一直告诉我做这样的事情:

Quaternion targetRotation = Quaternion.Euler(Vector3.zero);
rb.MoveRotation(Quaternion.Slerp(rb.rotation, targetRotation, rotationCorrectionSpeed));

但是 MoveRotation 行给出了错误:

参数 1:无法从“float”转换为“UnityEngine.Quaternion”

这是正确的方法吗?如果是这样,我该如何修复错误?或者有更好的方法吗?

unity-game-engine
  • 2 个回答
  • 34 Views
Martin Hope
soleil
Asked: 2024-11-01 11:54:56 +0800 CST

在 Unity 中单击并拖动 - 保持偏移

  • 5

以下代码用于单击并拖动对象:

    private void MousePressed(InputAction.CallbackContext context)
    {
        Vector2 mousePosition = Input.mousePosition;

        Vector3 worldPosition = mainCamera.ScreenToWorldPoint(new Vector3(mousePosition.x, mousePosition.y, -mainCamera.transform.position.z));
        worldPosition.z = 0;    

        Collider2D hitCollider = Physics2D.OverlapPoint(worldPosition);

        if (hitCollider != null)
        {
            StartCoroutine(DragUpdate(hitCollider.gameObject));
        }
    }

    private IEnumerator DragUpdate(GameObject clickedObject)
    {
        float initialDistance = Vector3.Distance(clickedObject.transform.position, mainCamera.transform.position);
        clickedObject.TryGetComponent<Rigidbody2D>(out var rb);
        while (mouseClick.ReadValue<float>() != 0) {
            Ray ray = mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue());

            if (rb != null) {
                Vector3 direction = ray.GetPoint(initialDistance) - clickedObject.transform.position;
                rb.velocity = direction * mouseDragPhysicsSpeed;
                yield return waitForFixedUpdate;
            } else {
                clickedObject.transform.position = Vector2.SmoothDamp(clickedObject.transform.position, ray.GetPoint(initialDistance), ref velocity, mouseDragSpeed);
                yield return null;
            }
        }
    }

问题是对象首先移动,使其中心位于光标上。如何保留初始偏移量,以便光标相对于对象的位置与第一次开始拖动时的位置相同?

我愿意接受任何改进此代码的建议 - 我是 Unity/C# 的新手。谢谢!

unity-game-engine
  • 1 个回答
  • 18 Views
Martin Hope
soleil
Asked: 2024-03-16 02:17:18 +0800 CST

SwiftUI 覆盖对齐水平居中

  • 6

我需要视图 A 在屏幕上居中(垂直和水平)。我需要视图 B 显示在视图 A 下方 30 像素处,也水平居中。但添加 B 时,A 必须保持在屏幕中央,不能向上移动。.overlay我可以通过使用and来完成大部分工作GeometryReader:

struct ContentView: View {
        
    var body: some View {
        VStack {
            ZStack {
                Rectangle()
                    .fill(.red)
                    .frame(width: 200, height: 100)
                    .overlay {
                        GeometryReader {geo in
                            Rectangle()
                                .fill(.blue)
                                .frame(width: 100, height: 100)
                                .offset(y: geo.size.height + 30)
                        }
                    }
            }
        }
    }
}

在此输入图像描述

我不知道如何使蓝色矩形水平居中。我不一定知道它的宽度,尽管这里出于视觉目的指定了它。假设我不知道任一视图的确切帧值,如何将 B 定位在 A 下面 30 像素处,同时将 A 保持在屏幕中心?有没有更好的视图结构来实现这一点?

swiftui
  • 2 个回答
  • 29 Views
Martin Hope
soleil
Asked: 2024-03-09 01:43:17 +0800 CST

仅在与交互时切换 onChange

  • 5

我正在显示一个清单,允许用户检查打开和关闭的选项:

ForEach(checklist.items.sorted(by: { $0.sortOrder < $1.sortOrder })) { item in
    @Bindable var item = item
    Toggle(item.title, isOn: $item.isChecked)
    .toggleStyle(CheckboxToggleStyle())
    .onChange(of: item.isChecked) { newValue in
        checklistChanged()
    }
}

func checklistChanged() {
    //check some things and update other parts of the UI
}

这很好用。然而,清单是一个 SwiftData @Model,它有一个重置清单的方法:

func reset() {
    for item in self.items {
        item.isChecked = false
    }
}

调用此函数会导致checklistChanged()我认为该函数被调用(多次),因为isChecked所有项目的属性都在更改。我只希望checklistChanged()当用户点击并更改复选框值时专门调用该函数。我怎样才能区分这些问题?我尝试使用onTapGesture而不是onChange在切换上,但没有被调用。

swift
  • 1 个回答
  • 37 Views
Martin Hope
soleil
Asked: 2024-02-26 01:26:41 +0800 CST

在 ruby​​ 中使用 Google Drive API 删除文件时出现权限问题

  • 5

我有一个 Google Apps 脚本,可以从电子表格选项卡创建 json 文件:

function makeJSON() {
  var spreadsheetId = 'someId'; 
  var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
  var sheets = spreadsheet.getSheets();
  var urls = []; // Array to store the URLs of the created files

  for (var i =  1; i < sheets.length; i++) {
    var sheet = sheets[i];
    var data = sheet.getRange(3,  1, sheet.getLastRow() -  2, sheet.getLastColumn()).getValues();
    var headers = sheet.getRange(2,  1,  1, sheet.getLastColumn()).getValues()[0];

    var objects = data.map(function(row) {
    var obj = {};
    for (var j =  0; j < headers.length; j++) {
      //process data
    }
    
    return obj;
    });


     // Convert the array of objects to a JSON string
    var json = JSON.stringify(objects, null,  2);
    
    // Create a blob from the JSON string
    var blob = Utilities.newBlob(json, 'application/json', sheet.getName() + '.json');

    var folder = DriveApp.getFolderById('someId');
    var file = folder.createFile(blob);

    file.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT); //I don't like making these publicly editable but it seems I'm forced to in order to be able to download/delete them via ruby script
    
    // Get the file ID
    var fileId = file.getId();
    
    // Construct the direct download URL
    var directDownloadUrl = "https://drive.google.com/uc?export=download&id=" + fileId;
    
    // Add the direct download URL to the array
    urls.push(directDownloadUrl);
    
  }
  return urls;
}

function doGet() {
  var urls = makeJSON(); // Call the function to generate JSON files and get their URLs
  return ContentService.createTextOutput(JSON.stringify({urls: urls})).setMimeType(ContentService.MimeType.JSON);
}

我有一个 ruby​​ 脚本,可以从 Google Drive 下载所有这些文件。那部分有效。但我也想在下载后删除它们:

drive_service = Google::Apis::DriveV3::DriveService.new
scope = 'https://www.googleapis.com/auth/drive'

authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('google_client.json'),
  scope: scope
)

authorizer.fetch_access_token!

# Set the authorization for the Drive API client
drive_service.authorization = authorizer

# URL of your deployed web app that returns JSON file URLs
web_app_url = 'https://script.google.com/macros/s/digits/exec'

# Fetch the JSON data from the web app
response = URI.open(web_app_url).read
json_data = JSON.parse(response)

# Directory to save the JSON files
save_directory = 'downloads'

# Ensure the directory exists
FileUtils.mkdir_p(save_directory) unless File.directory?(save_directory)

json_data['urls'].each do |url|
  # Extract the file ID from the URL
  file_id = url.split('id=')[1]
   
  # Fetch the file's metadata using the Google Drive API
  file_metadata = drive_service.get_file(file_id, fields: 'name')
   
  # Extract the file name
  file_name = file_metadata.name
   
  # Construct the direct download URL
  direct_download_url = "https://drive.google.com/uc?export=download&id=#{file_id}"
   
  # Construct the full path
  file_path = File.join(save_directory, file_name)
   
  # Download the file
  URI.open(direct_download_url) do |source|
    File.open(file_path, 'wb') do |file|
      file.write(source.read)
    end
  end
  puts "Saved #{file_name} to #{save_directory}"

  # Delete the file from Google Drive
  drive_service.delete_file(file_id) #THIS LINE THROWS THE ERROR
end

这是错误:

/Users/me/.rvm/gems/ruby-2.7.2/gems/google-apis-core-0.14.0/lib/google/apis/core/http_command.rb:244:in `check_status': insufficientFilePermissions: The user does not have sufficient permissions for this file. (Google::Apis::ClientError)

我认为问题在于,在我的 ruby​​ 脚本中,凭据来自我的服务帐户([email protected]),而 Google Drive 上的文件归“我”所有([email protected])。但我不知道如何让它们首先归我的服务帐户所有,也不知道如何使用我的常规电子邮件帐户凭据运行脚本。当您在云控制台中创建服务帐户时,它会强制您使用*.iam.gserviceaccount.com帐户。

Google 云端硬盘文件夹与我的服务帐户共享。其中的所有文件均归“我”所有,并且我的服务帐户对所有文件都具有编辑者权限。

那么,话虽如此,下载这些文件后如何从 Google 云端硬盘中删除它们呢?文件堆积得很快,我需要保持这个目录干净。

  • 1 个回答
  • 27 Views
Martin Hope
soleil
Asked: 2024-02-18 02:45:01 +0800 CST

当关系可选时的 SwiftData 谓词

  • 5

考虑 SwiftData 中的以下关系:

@Model
class Category: Decodable, Identifiable {
    var id: Int
    var title: String
    @Relationship var questions = [Question]() 
}

 @Model
 class Question: Decodable, Identifiable {
    var id: Int
    @Relationship var category: Category?
 }

当我在保存问题后尝试从类别中获取所有问题时,就会出现问题:

let catId = 7
let categoryPredicate = #Predicate<Category> { $0.id == catId }
let categoryDescriptor = FetchDescriptor(predicate: categoryPredicate)
let categories = try modelContext.fetch(categoryDescriptor)
if let cat = categories.first {
    cat.questions = parsedQuestions
}

//now try to fetch the questions out of the modelContext so they can be used and updated 
let questionPredicate = #Predicate<Question> { $0.category.id == catId } //THIS LINE THROWS THE ERRORS
let questionDescriptor = FetchDescriptor(predicate: questionPredicate)
            
do {
    questions = try modelContext.fetch(questionDescriptor)
} catch {
    fatalError("unable to find any questions for \(category.title)")
}

我收到这组错误:

无法推断通用参数“ID”
在“可选”上引用实例方法“id”要求“类别”符合“视图”
类型“(ID)->某些视图”不能符合“BinaryInteger”

在这种情况下,如何编写正确的谓词而不出现错误?

swift
  • 1 个回答
  • 28 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve