嗨,我无法将渐变色应用于UIView
。它是正确应用,但颜色界限随着水平&而变化纵向。
如果我在纵向方向上正确设置,则当我将设备翻转到水平时,不会更改渐变视图的边界。
那么,如何为水平和纵向设备方向获得UIView
的正确约束和大小?
非常感谢你的帮助!
我尝试过的代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet var viewBar: UIView!
override func viewDidLoad() {
super.viewDidLoad()
viewBar.layer.shadowOpacity = 0.5
viewBar.layer.shadowOffset = CGSize(width: 3.0, height:2.0)
viewBar.layer.shadowRadius = 5.0
viewBar.layer.shadowColor = UIColor.blueColor().CGColor
let gradient: CAGradientLayer = CAGradientLayer()
gradient.colors = [UIColor.blueColor().CGColor, UIColor.redColor().CGColor]
gradient.locations = [0.0 , 1.0]
gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
gradient.frame.size = self.viewBar.bounds.size
self.viewBar.layer.insertSublayer(gradient, atIndex: 0)
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
编码输出:
答案 0 :(得分:7)
在viewDidLoad
中,布局尚未发生,因此您的框架错误,将gradient.frame.size = self.viewBar.bounds.size
移至viewDidLayoutSubviews:
或viewWillAppear:
,以便{{1}得到正确的框架。
gradient
答案 1 :(得分:2)
使用此方法检查viewDidLayoutSubViews中的设备方向。
+(NSString*)checkDeviceOrientation
{
NSString *deviceOrientation;
if ([[UIDevice currentDevice]orientation]== UIInterfaceOrientationLandscapeLeft ) {
deviceOrientation = @"landscape left mode";
}
else if ([[UIDevice currentDevice]orientation]==UIInterfaceOrientationLandscapeRight){
deviceOrientation = @"landscape right mode";
}
else{
deviceOrientation = @"potrait mode";
}
return deviceOrientation;
}
然后在viewDidLayoutSubviews中 像这样调用这个函数,
-(void)viewDidLayoutSubview
{
if(IS_PHONE4)
if([self.checkDeviceOrientation isEqualtoString;@"landscape right mode"])
{
NSLog(@"Get your view size%@",self.view.frame.size.width);
}
if(IS_IPHONE5)
if([self.checkDeviceOrientation isEqualtoString;@"landscape right mode"])
{
NSLog(@"Get your view size%@",self.view.frame.size.width);
}
.....
}
还要记住将这些常量放在任何文件中。
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPHONE4 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 480.0f || IS_IPHONE && [[UIScreen mainScreen]bounds].size.width == 480.0f)
#define IS_IPHONE5 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 568.0f || IS_IPHONE && [[UIScreen mainScreen]bounds].size.width == 568.0f)
#define IS_IPHONE6 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 667.0 || IS_IPHONE && [[UIScreen mainScreen]bounds].size.width == 667.0f)
#define IS_IPHONE6PLUS (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 736.0 || IS_IPHONE && [[UIScreen mainScreen]bounds].size.width == 736.0f)
#define IS_RETINA ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale == 2.0))
我不熟悉Swift代码,但希望,它会对你有帮助。