当附加到无图像时,框架修改器为什么仍会影响其他视图?

如何解决当附加到无图像时,框架修改器为什么仍会影响其他视图?

self.imagesViewModel.allImages[post.imageContentURL]?
    .resizable()
    .scaledToFill()
    .frame(width: 343,height: 171,alignment: .center)
    .clipShape(Rectangle())
    .shadow(radius: 1)

当返回的图像值为nil时,此代码应执行的操作无济于事。但是无论出于何种原因,.frame修饰符仍然会影响滚动视图内的其他元素。最终会在物理上而不是在视觉上阻碍导航链接。

我已经确认删除.frame后,一切都会按照我的预期进行。但是我需要对图像设置限制,所以我不能没有类似的东西。

我尝试将代码放在if语句中以检查nil并仅在返回的图像上显示,但这没有用。此代码的其他变体也不起作用。

if self.imagesViewModel.allImages[post.imageContentURL] != nil {
    self.imagesViewModel.allImages[post.imageContentURL]?
        .resizable()
        .scaledToFill()
        .frame(width: 343,height: 171)
        .clipShape(Rectangle())
        .shadow(radius: 1)
}

我也尝试过将最小值设置为零,但是没有运气。

我想知道这是否与我在Xcode 12 beta 5上使用新的SwiftUI应用程序生命周期有关。在iPhone(iOS 14)上运行代码时,我遇到了相同的物理障碍,但是在scrollview元素之间添加了额外的视觉间距。

这是我的代码的简化版本,可以复制我的问题:

import SwiftUI
import Combine

struct Post: Codable,Identifiable {
    var id: Int
    var text: String
    var imageContentURL: String?
}

class PostsViewModel: ObservableObject {
    @Published var posts: [Post] = []
}

class ImagesViewModel: ObservableObject {
    @Published var allImages: [String?: Image] = [:]
}

/// The View of the content displayed in Home
struct PostLayout: View {
    @EnvironmentObject var imagesViewModel: ImagesViewModel
    var post: Post
    
    init(post: Post) {
        self.post = post
    }
    
    var body: some View {
        VStack {
            // This is the navigation link that gets obstructed
            NavigationLink(destination: SomeOtherView()) {
                Image(systemName: "circle.fill")
                    .resizable()
                    .frame(width: 48,height: 48)
                    .clipShape(Circle())
            }
            
            Text(self.post.text)
            
            // MARK: This is the problem code,border added for clarity
            self.imagesViewModel.allImages[self.post.imageContentURL]?
                .resizable()
                .scaledToFill()
                .frame(width: 343,height: 171)
                .clipShape(Rectangle())
                .shadow(radius: 1)
                .border(Color.black,width: 1)
        }
        .border(Color.black,width: 1)
    }
}

/// View that is navigated to from Home
struct SomeOtherView: View {
    var body: some View {
        Text("SomeOtherView")
    }
}

/// Main displayed view
struct Home: View {
    @EnvironmentObject var postsViewModel: PostsViewModel
    @EnvironmentObject var imagesViewModel: ImagesViewModel

    var body: some View {
        NavigationView {
            ScrollView {
                ForEach(self.postsViewModel.posts) { post in
                    PostLayout(post: post)
                }
            }
            .onAppear() {
                // All displayed content created here
                var post1 = Post(id: 0,text: "Content")
                let post2 = Post(id: 1,text: "Content")
                var post3 = Post(id: 2,text: "Content")
                let post4 = Post(id: 3,text: "Content")
                let imageURL = "someImageURL"
                
                self.imagesViewModel.allImages[imageURL] = Image(systemName: "circle")
                
                // Only two posts are supposed to have an imageURL
                post1.imageContentURL = imageURL
                post3.imageContentURL = imageURL
                self.postsViewModel.posts.append(contentsOf: [post1,post2,post3,post4])
            }
            .navigationTitle("Home")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Home()
            .environmentObject(PostsViewModel())
            .environmentObject(ImagesViewModel())
    }
}

解决方法

您已经注意到.frame修饰符不是特定于图像的。即使图片为nil也可以使用。

您可以做的是检查Image是否可以加载。您可以使用UIImage(named:)(返回可选)来完成此操作:

@ViewBuilder
var body: some View {
    if UIImage(named: "imageName") != nil {
        Image("imageName")
            .resizable()
            .scaledToFill()
            .frame(width: 343,height: 171,alignment: .center)
            ...
    }
}

或者,或者:

@ViewBuilder
var body: some View {
    if imagesViewModel.allImages[post.imageContentURL] != nil {
        imagesViewModel.allImages[post.imageContentURL]!
            .resizable()
            .scaledToFill()
            .frame(width: 343,alignment: .center)
            ...
    }
}

编辑

在字典中不需要可选的String?。只需将其替换为:

@Published var allImages: [String: Image] = [:]

然后使用if语句检查图像是否不为零(在Xcode 12中,您也可以使用if-let):

if self.post.imageContentURL != nil {
    self.imagesViewModel.allImages[self.post.imageContentURL!]?
        .resizable()
        .scaledToFill()
        .frame(width: 343,height: 171)
        .clipShape(Rectangle())
        .shadow(radius: 1)
        .border(Color.black,width: 1)
}
,

结果发现问题与nil或frame修饰符无关。

该图像实际上无形地延伸到.clipShape(Rectangle())的边界之外,并阻塞了NavigationLink。解决方案是结合使用.contentShape().clipped

self.imagesViewModel.allImages[self.post.imageContentURL]?
    .resizable()
    .scaledToFill()
    .frame(width: 343,height: 171)
    .contentShape(Rectangle())
    .clipped()
    .shadow(radius: 1)

我从这里的帖子中发现了这个答案: Clipped Image calls TapAction outside frame

,

可能是实际的图像有问题,但是存在类型Image的SwiftUI视图。 Image更像UIImageView而不是UIImage,尽管将它看作是两者实际上并没有帮助。您可能想要的是:

    var body: some View {
        if imageView == nil {
            EmptyView()
        } else {
            imageView?
                .resizable()
                .scaledToFill()
                .frame(width: 343,alignment: .center)
                .clipShape(Rectangle())
                .shadow(radius: 1)
                .border(Color.black)
        }
    }
,

您可以简单地使用if-let(Xcode 12 +):

if let image = self.imagesViewModel.allImages[post.imageContentURL]? {
    image
    .resizable()
    .scaledToFill()
    .frame(width: 343,alignment: .center)
    .clipShape(Rectangle())
    .shadow(radius: 1)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res