关于在storyboard拖按钮控件,手动设置代码不成功的问题

首先,在 storyboard 中拖拽一个按钮控件.设置好约束条件

然后把该控件作为属性,拖线到控制器当中

拿到控件属性后,可以在控制器当中用代码进行设置图片信息,我们以下载网络图片为例:

 1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 2 {
 3     
 4     // 1.开启异步线程
 5     dispatch_async(dispatch_get_global_queue(0, 0), ^{
 6         
 7         // 1.1.获取网络图片 url 地址
 8         NSURL *url = [NSURL URLWithString:@"http://photo.scol.com.cn/hdp/img/attachement/jpg/site2/20101230/00219b7b06490e861d3d54.jpg"];
 9 
10         // 1.2.根据 url 进行下载图片
11         NSData *data = [NSData dataWithContentsOfURL:url];
12 
13         // 2.回到主线程设置下载好的图片
14         dispatch_sync(dispatch_get_main_queue(), ^{
15             // 2.1.设置按钮上面的图片
16             [self.btn setImage:[UIImage imageWithData:data] forState:UIControlStateNormal];
17         });
18     });
19 }

点击运行后,可见如下错误: 

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

错误原因:在 ios9开始,苹果把 HTTP 协议默认为不安全协议,建议采用 HTTPS 协议.

解决方案:在项目的 nfo.plis 文件中,加入App Transport Security Settings,Type:Dictionary.在其子内容中加入:Allow Arbitrary Loads,Type:Boolean,Value 选择 YES

示例:

保存后,再次运行代码:

问题:发现运行效果仍旧不是我们想要的.此处我们想要见到的效果是,按钮上面应该展示为我们网络上面下载来的图片,而此处现在显示的结果为按钮颜色由黄色变为了蓝色.

原因:由于拖拽过来的控件,属性(Type)默认为:System,系统样式不能够通过代码直接设置图片.

解决:把 Type的值修改为:Custom 即可.再次运行程序

设置成功!

posted @ 2016-01-08 12:37  晒太阳的仙人掌  阅读(296)  评论(0编辑  收藏  举报